pass argument to __enter__

Ramy picture Ramy · Feb 24, 2011 · Viewed 16.9k times · Source

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?

Answer

S.Lott picture S.Lott · Feb 24, 2011

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