|
4 | 4 | import _collections_abc |
5 | 5 | from collections import deque |
6 | 6 | from functools import wraps |
| 7 | +from types import MethodType |
7 | 8 |
|
8 | 9 | __all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext", |
9 | 10 | "AbstractContextManager", "AbstractAsyncContextManager", |
@@ -373,9 +374,7 @@ class _BaseExitStack: |
373 | 374 |
|
374 | 375 | @staticmethod |
375 | 376 | def _create_exit_wrapper(cm, cm_exit): |
376 | | - def _exit_wrapper(exc_type, exc, tb): |
377 | | - return cm_exit(cm, exc_type, exc, tb) |
378 | | - return _exit_wrapper |
| 377 | + return MethodType(cm_exit, cm) |
379 | 378 |
|
380 | 379 | @staticmethod |
381 | 380 | def _create_cb_wrapper(callback, *args, **kwds): |
@@ -443,7 +442,6 @@ def callback(self, callback, *args, **kwds): |
443 | 442 | def _push_cm_exit(self, cm, cm_exit): |
444 | 443 | """Helper to correctly register callbacks to __exit__ methods.""" |
445 | 444 | _exit_wrapper = self._create_exit_wrapper(cm, cm_exit) |
446 | | - _exit_wrapper.__self__ = cm |
447 | 445 | self._push_exit_callback(_exit_wrapper, True) |
448 | 446 |
|
449 | 447 | def _push_exit_callback(self, callback, is_sync=True): |
@@ -535,9 +533,7 @@ class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager): |
535 | 533 |
|
536 | 534 | @staticmethod |
537 | 535 | def _create_async_exit_wrapper(cm, cm_exit): |
538 | | - async def _exit_wrapper(exc_type, exc, tb): |
539 | | - return await cm_exit(cm, exc_type, exc, tb) |
540 | | - return _exit_wrapper |
| 536 | + return MethodType(cm_exit, cm) |
541 | 537 |
|
542 | 538 | @staticmethod |
543 | 539 | def _create_async_cb_wrapper(callback, *args, **kwds): |
@@ -596,7 +592,6 @@ def _push_async_cm_exit(self, cm, cm_exit): |
596 | 592 | """Helper to correctly register coroutine function to __aexit__ |
597 | 593 | method.""" |
598 | 594 | _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit) |
599 | | - _exit_wrapper.__self__ = cm |
600 | 595 | self._push_exit_callback(_exit_wrapper, False) |
601 | 596 |
|
602 | 597 | async def __aenter__(self): |
|
0 commit comments