0

Consider the following code:

class Foo():
    def __enter__(self):
        print("ENTER")
        self.age = 23
    def __exit__(self, exc_type, exc_value, traceback):
        print("EXIT")
    def __init__(self, name):
        print("INIT")
        self.name = name

>>> with Foo("dave") as f:
...     print("HELLO")
... 
INIT
ENTER
HELLO
EXIT
>>> with Foo("dave") as f:
...     print(f.name)
... 
INIT
ENTER
EXIT
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'NoneType' object has no attribute 'name'
>>> f = Foo("dave")
INIT
>>> 
>>> f.name
'dave'

My question, why is name attribute not defined using context manager? Actually, why is it a NoneType object when I am trying to access name?

  • Does this answer your question? [\_\_init\_\_ vs \_\_enter\_\_ in context managers](https://stackoverflow.com/questions/39611520/init-vs-enter-in-context-managers) – Passerby Nov 23 '21 at 23:28
  • 1
    Your `__enter__` returns None. That is what you are trying to get `name` from. – khelwood Nov 23 '21 at 23:30

0 Answers0