contextlib.nullcontext (enter_result = None)
enter_result - The result to be passed to as.
The resulting context manager does nothing but return from its __enter__ ( ) what was passed to the function as an argument.
This can be useful if you are using a context manager, which is optional, depending on the circumstances.
from contextlib import nullcontext, contextmanager
@contextmanager
def my_manager ():
yield ’managed’
def maybe_managed (manage):
manager = my_manager () if manage else nullcontext (’not managed’)
with manager as managed:
print (managed)
maybe_managed (True) # managed
maybe_managed (False) # not managed