Search code examples
pythonwith-statement

pass argument to __enter__


Just learning about with statements especially from this article

question is, can I pass an argument to __enter__?

I have code like this:

class clippy_runner:
    def __enter__(self):
        self.engine = ExcelConnection(filename = "clippytest\Test.xlsx")
        self.db = SQLConnection(param_dict = DATASOURCES[STAGE_RELATIONAL])

        self.engine.connect()
        self.db.connect()

        return self

I'd like to pass filename and param_dict as parameters to __enter__. Is that possible?


Solution

  • Yes, you can get the effect by adding a little more code.

    
        #!/usr/bin/env python
    
        class Clippy_Runner( dict ):
            def __init__( self ):
                pass
            def __call__( self, **kwargs ):
                self.update( kwargs )
                return self
            def __enter__( self ):
                return self
            def __exit__( self, exc_type, exc_val, exc_tb ):
                self.clear()
    
        clippy_runner = Clippy_Runner()
    
        print clippy_runner.get('verbose')     # Outputs None
        with clippy_runner(verbose=True):
            print clippy_runner.get('verbose') # Outputs True
        print clippy_runner.get('verbose')     # Outputs None