Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 629
Ramy Avatar asked Feb 24 '11 19:02

Ramy


People also ask

What does __ enter __ do in Python?

__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.

What is __ exit __ in Python?

__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.

What is Contextlib?

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.

Which methods are invoked on entering?

__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.


1 Answers

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 
like image 113
S.Lott Avatar answered Sep 21 '22 02:09

S.Lott