The with statement applies to instances having 2 methods: "__enter__" and "__exit__". When the with statement is encountered, the instance's __enter__ method is called and its return value is used for the 'as' part of the statement. When the block exits, the instance's __exit__ method is called to perform cleanup action. In the case of a file object, the __exit__ method closes the file.
return "block value"
def __exit__(self, *args):
with A() as value:
my output -->
An alternative to writing a class to create such 'context' instances is to write a function with a single "yield" statement and use the contextmanager decorator like this
from contextlib import contextmanager
yield "block value"
with B() as value:
""" my output -->
As a more useful example, here is a context which executes a block of statement in a given directory and comes back to the initial directory at the end of the block
old = os.getcwd()
yield # this is where the code in the "with" block will be executed