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?
__enter__() is provided which returns self while object. __exit__() is an abstract method which by default returns None . See also the definition of Context Manager Types. New in version 3.6.
__exit__ in Python Context manager is used for managing resources used by the program. After completion of usage, we have to release memory and terminate connections between files.
Overview. The contextlib module of Python's standard library provides utilities for resource allocation to the with statement. The with statement in Python is used for resource management and exception handling. Therefore, it serves as a good Context Manager.
__enter__ and [__exit__] both are methods that are invoked on entry to and exit from the body of "the with statement" (PEP 343) and implementation of both is called context manager. the with statement is intend to hiding flow control of try finally clause and make the code inscrutable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With