Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import _collections_abc
from collections import deque
from functools import wraps
from types import MethodType

__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
"AbstractContextManager", "AbstractAsyncContextManager",
Expand Down Expand Up @@ -373,9 +374,7 @@ class _BaseExitStack:

@staticmethod
def _create_exit_wrapper(cm, cm_exit):
def _exit_wrapper(exc_type, exc, tb):
return cm_exit(cm, exc_type, exc, tb)
return _exit_wrapper
return MethodType(cm_exit, cm)

@staticmethod
def _create_cb_wrapper(callback, *args, **kwds):
Expand Down Expand Up @@ -443,7 +442,6 @@ def callback(self, callback, *args, **kwds):
def _push_cm_exit(self, cm, cm_exit):
"""Helper to correctly register callbacks to __exit__ methods."""
_exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
_exit_wrapper.__self__ = cm
self._push_exit_callback(_exit_wrapper, True)

def _push_exit_callback(self, callback, is_sync=True):
Expand Down Expand Up @@ -535,9 +533,7 @@ class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager):

@staticmethod
def _create_async_exit_wrapper(cm, cm_exit):
async def _exit_wrapper(exc_type, exc, tb):
return await cm_exit(cm, exc_type, exc, tb)
return _exit_wrapper
return MethodType(cm_exit, cm)

@staticmethod
def _create_async_cb_wrapper(callback, *args, **kwds):
Expand Down Expand Up @@ -596,7 +592,6 @@ def _push_async_cm_exit(self, cm, cm_exit):
"""Helper to correctly register coroutine function to __aexit__
method."""
_exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit)
_exit_wrapper.__self__ = cm
self._push_exit_callback(_exit_wrapper, False)

async def __aenter__(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
``contextlib.ExitStack`` and ``contextlib.AsyncExitStack`` now use a method
instead of a wrapper function for exit callbacks.