contextlib.nullcontext in Python

Python Methods and Functions

Returns a dummy context manager.

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 

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

Get Solution for free from DataCamp guru