pass argument to __enter__
No. You can't. You pass arguments to __init__()
.
class ClippyRunner:
def __init__(self, *args):
self._args = args
def __enter__(self):
# Do something with args
print(self._args)
with ClippyRunner(args) as something:
# work with "something"
pass
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