Object becomes None when using a context manager

Weholt picture Weholt · Feb 23, 2011 · Viewed 22.3k times · Source

Why doesn`t this work:

class X:
    var1 = 1
    def __enter__(self): pass
    def __exit__(self, type, value, traceback): pass

with X() as z:
    print z.var1

I get:

print z.var1
AttributeError: 'NoneType' object has no attribute 'var1'

Answer

Sven Marnach picture Sven Marnach · Feb 23, 2011

Change the definition of X to

class X(object):
    var1 = 1
    def __enter__(self):
        return self
    def __exit__(self, type, value, traceback):
        pass

with assigns the return value of the __enter__() method to the name after as. Your __enter__() returned None, which was assigned to z.

I also changed the class to a new-style class (which is not critical to make it work).