|  | 
| 1 |  | -from contextlib import contextmanager | 
|  | 1 | +@object.__new__ | 
|  | 2 | +class nop_context(object): | 
|  | 3 | +    """A nop context manager. | 
|  | 4 | +    """ | 
|  | 5 | +    def __enter__(self): | 
|  | 6 | +        pass | 
|  | 7 | + | 
|  | 8 | +    def __exit__(self, *excinfo): | 
|  | 9 | +        pass | 
| 2 | 10 | 
 | 
| 3 | 11 | 
 | 
| 4 | 12 | def _nop(*args, **kwargs): | 
| @@ -44,17 +52,22 @@ class CallbackManager(object): | 
| 44 | 52 |     exiting another block | 
| 45 | 53 |     """ | 
| 46 | 54 |     def __init__(self, pre=None, post=None): | 
| 47 |  | -        pre = pre if pre is not None else _nop | 
| 48 |  | -        post = post if post is not None else _nop | 
|  | 55 | +        self.pre = pre if pre is not None else _nop | 
|  | 56 | +        self.post = post if post is not None else _nop | 
|  | 57 | + | 
|  | 58 | +    def __call__(self, *args, **kwargs): | 
|  | 59 | +        return _ManagedCallbackContext(self.pre, self.post, args, kwargs) | 
| 49 | 60 | 
 | 
| 50 |  | -        @contextmanager | 
| 51 |  | -        def _callback_manager_context(*args, **kwargs): | 
| 52 |  | -            try: | 
| 53 |  | -                yield pre(*args, **kwargs) | 
| 54 |  | -            finally: | 
| 55 |  | -                post(*args, **kwargs) | 
| 56 | 61 | 
 | 
| 57 |  | -        self._callback_manager_context = _callback_manager_context | 
|  | 62 | +class _ManagedCallbackContext(object): | 
|  | 63 | +    def __init__(self, pre, post, args, kwargs): | 
|  | 64 | +        self._pre = pre | 
|  | 65 | +        self._post = post | 
|  | 66 | +        self._args = args | 
|  | 67 | +        self._kwargs = kwargs | 
| 58 | 68 | 
 | 
| 59 |  | -    def __call__(self, *args, **kwargs): | 
| 60 |  | -        return self._callback_manager_context(*args, **kwargs) | 
|  | 69 | +    def __enter__(self): | 
|  | 70 | +        return self._pre(*self._args, **self._kwargs) | 
|  | 71 | + | 
|  | 72 | +    def __exit__(self, *excinfo): | 
|  | 73 | +        self._post(*self._args, **self._kwargs) | 
0 commit comments