Skip to content

Instantly share code, notes, and snippets.

@fortune
Created March 7, 2012 02:22
Show Gist options
  • Save fortune/1990488 to your computer and use it in GitHub Desktop.
Save fortune/1990488 to your computer and use it in GitHub Desktop.
Python の contextlib モジュールの contextmanager のようなものを自前で書くとどんな感じになるか?
def my_contextmanager(function):
class Context(object):
def __init__(self, *args, **kw):
self.ctx = function(*args, **kw)
def __enter__(self):
return self.ctx.next()
def __exit__(self, exception_type, exception_value, exception_traceback):
try:
if exception_type is None:
self.ctx.next()
else:
self.ctx.throw(exception_type, exception_value, exception_traceback)
except StopIteration:
return True
else:
return True
def _my_contextmanager(*args, **kw):
return Context(*args, **kw)
return _my_contextmanager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment