Skip to content

Instantly share code, notes, and snippets.

@antvconst
Created November 17, 2019 18:44
Show Gist options
  • Save antvconst/ef583aa89cde39fd6ad620cc1cd57115 to your computer and use it in GitHub Desktop.
Save antvconst/ef583aa89cde39fd6ad620cc1cd57115 to your computer and use it in GitHub Desktop.
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