pythoncontextmanager

How to make a python context manager


I define my class like this:

class Simple():
    def __init__(self):
        self.string = "Hello World"

    def __enter__(self):
        pass

    def __exit__(self):
        pass

and call it like this:

with Simple() as simple_test:
    print(simple_test.string)

I get the following error:

    print(simple_test.string)
AttributeError: 'NoneType' object has no attribute 'string'

Why is my class None?


Solution

  • The __enter__ method must return self:

    def __enter__(self):
        return self