Return a context manager that returns enter_result from __enter__, but otherwise does nothing. It is intended to be used as a stand-in for an optional context manager, for example:
contextlib.nullcontext(enter_result=None)
def myfunction(arg, ignore_exceptions=False):
if ignore_exceptions:
Use suppress to ignore all exceptions.
cm = contextlib.suppress(Exception)
else:
Do not ignore any exceptions, cm has no effect.
cm = contextlib.nullcontext()
with cm:
Do something
def process_file(file_or_path):
if isinstance(file_or_path, str):
If string, open file
cm = open(file_or_path)
else:
Caller is responsible for closing file
cm = nullcontext(file_or_path)
with cm as file:
Perform processing on the file
async def send_http(session=None):
if not session:
If no http session, create it with aiohttp
cm = aiohttp.ClientSession()
else:
Caller is responsible for closing the session
cm = nullcontext(session)
async with cm as session:
Send http requests with session