For example, i have this code:
with MyClass() as x:
print 'I have only {0}'.format(x)
with MyClass() as y:
print 'I have {0} and {1}'.format(x, y)
print 'Again only {0}'.format(x)
x and y both should be de-initialized after exit of corresponding with blocks. Also x and y aren’t instances of MyClass.
__exit__ has only three arguments and each argument is None (if no exception supplied).
How can i determine at __exit__ which block is just exited and what value was returned by __enter__?
(N.B. code should be thread-safe).
Example:
class MyClass(object):
def __enter__(self):
if moon_phase > 0:
return 123
else:
return 456
def __exit__(self):
number = what_was_returned_by_enter()
print 'End of block with', number
with MyClass() as x:
print x # 123
with MyClass() as y:
print x, 'and', y # 123 and 456
# printed "End of block with 456"
print x # 123
# printed "End of block with 123"
Since you have a custom class handling your context,
selfwill be the context manager instance.You’ll need to examine its state (stored at
__init__()creation time or when__enter__()was called) to determine which one you just exited.The following example stores the return value of
__enter__on the instance so you can retrieve it again when__exit__is being called: