Suppose we have the following mod.py
:
def __enter__():
print("__enter__<")
def __exit__(*exc):
print("__exit__< {0}".format(exc))
class cls:
def __enter__(self):
print("cls.__enter__<")
def __exit__(self, *exc):
print("cls.__exit__< {0}".format(exc))
and the following use of it:
import mod
with mod:
pass
I get an error:
Traceback (most recent call last):
File "./test.py", line 3, in <module>
with mod:
AttributeError: __exit__
According to the documentation the documentation the with
statement should execute as follows (I believe it fails at step 2 and therefore truncate the list):
- The context expression (the expression given in the with_item) is evaluated to obtain a context manager.
- The context manager’s
__exit__()
is loaded for later use.- The context manager’s
__enter__()
method is invoked.- etc...
As I've understood it there is no reason why __exit__
could not be found. Is there something I've missed that makes a module not able to work as a context manager?