Created
November 17, 2019 18:44
-
-
Save antvconst/ef583aa89cde39fd6ad620cc1cd57115 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
def contextmanager(function): | |
@functools.wraps(function) | |
def contextmanager_impl(*args, **kwargs): | |
class contextmanager_impl_(object): | |
def __init__(self): | |
self.gen = function(*args, **kwargs) | |
self.it = None | |
def __enter__(self): | |
self.it = iter(self.gen) | |
return next(self.it) | |
def __exit__(self, exception_type, exception_value, traceback): | |
try: | |
if exception_value is not None: | |
self.it.throw(exception_value) | |
else: | |
next(self.it) | |
except StopIteration: | |
pass | |
return True | |
return contextmanager_impl_() | |
return contextmanager_impl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment