CKTIS / Python
contextlib.nullcontext
Supplies a no-operation context manager that optionally returns a provided value.
Version: Python 3.14; repository image, production runtime not attested
Syntax
contextlib.nullcontext(enter_result=None)Supplies a no-operation context manager that optionally returns a provided value.
A borrowed resource stays open after exit, making it possible to use the same control flow with owned and borrowed resources.
Stand in for an optional context manager, passing enter_result through unchanged. By default the entered value is None. Exit does no cleanup and does not suppress body errors. Since 3.10 it also works with async with. The borrowed StringIO still belongs to the caller, so closed is False after reading oak.
import asyncio
from contextlib import nullcontext
from io import StringIO
s = StringIO("x")
with nullcontext(s) as value:
assert value is s
assert not s.closed
async def main():
async with nullcontext(s) as value:
assert value is s
asyncio.run(main())
s.close()
Examples
import contextlib
from io import StringIO
stream = StringIO("oak")
with contextlib.nullcontext(stream) as file:
print(file.read())
print(stream.closed)
stream.close()
Result
oak False
Stand in for an optional context manager, passing enter_result through unchanged. By default the entered value is None. Exit does no cleanup and does not suppress body errors. Since 3.10 it also works with async with. The borrowed StringIO still belongs to the caller, so closed is False after reading oak.