Search code examples
pythoncontextmanager

How can I access attributes of a context manager?


I want to accomplish something like:

class my_context(object):
    def __init__(self):
        self.obj1 = Obj()
        self.obj2 = Obj()
        ...

    def __enter__(self):
        ''' initialize objects '''

    def __exit__(self, type, value, tb):
        ''' uninitialize objects '''

There are many Obj attributes which are resources which need to be be closed/deleted/etc. I was hoping to use a context manager to set them up and then get rid of them. However what I've found is that I cannot access the attributes when I try:

with my_context() as cont:
    cont.obj1  # doesn't work

Is there a way I can access these attributes?


Solution

  • For the with... as syntax to work, your __enter__() must return a value.

    If you want to use the same attributes as your my_context class provides, you probably want to return self.