with cm as file:
# Perform processing on the file
+ It can also be used as a stand-in for
+ :ref:`asynchronous context managers <async-context-managers>`::
+
+ 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
+
.. versionadded:: 3.7
+ .. versionchanged:: 3.10
+ :term:`asynchronous context manager` support was added.
+
+
.. function:: suppress(*exceptions)
return received_exc and suppressed_exc
-class nullcontext(AbstractContextManager):
+class nullcontext(AbstractContextManager, AbstractAsyncContextManager):
"""Context manager that does no additional processing.
Used as a stand-in for a normal context manager, when a particular
def __exit__(self, *excinfo):
pass
+
+ async def __aenter__(self):
+ return self.enter_result
+
+ async def __aexit__(self, *excinfo):
+ pass
import asyncio
-from contextlib import aclosing, asynccontextmanager, AbstractAsyncContextManager, AsyncExitStack
+from contextlib import (
+ asynccontextmanager, AbstractAsyncContextManager,
+ AsyncExitStack, nullcontext, aclosing)
import functools
from test import support
import unittest
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)
+class TestAsyncNullcontext(unittest.TestCase):
+ @_async_test
+ async def test_async_nullcontext(self):
+ class C:
+ pass
+ c = C()
+ async with nullcontext(c) as c_in:
+ self.assertIs(c_in, c)
+
+
if __name__ == '__main__':
unittest.main()
--- /dev/null
+Add async context manager support for contextlib.nullcontext.