With instruction sets a variable to None

I am trying to run this code:

class A:
    def __enter__(self):
        print "enter"
    def __exit__(self, *args):
        print "exit"
    def __init__(self, i):
        self.i = i
with A(10) as a:
    print a.i

And I get this error:

enter
exit
Traceback (most recent call last):
File ".last_tmp.py", line 9, in <module>
print a.i
AttributeError: 'NoneType' object has no attribute 'i'

What is wrong with my syntax?

+4
source share
2 answers

You will need to return selffrom __enter__:

def __enter__(self):
    print "enter"
    return self

Your statement is withactually equivalent to:

a = A(10).__enter__()  # with A(10) as a:
try:
    print a.i  # Your with body
except:
    a.__exit__(exception and type)
    raise
else:
    a.__exit__(None, None, None)

So, you need to return something, otherwise it awill have a value None(default return value), but Nonedoes not have an attribute with a name i, so you will get AttributeError.

+10
source

__enter__ - , , as. () None, , . __enter__ self, , A(10), a.

+2

All Articles