Created
March 7, 2012 02:22
-
-
Save fortune/1990488 to your computer and use it in GitHub Desktop.
Python の contextlib モジュールの contextmanager のようなものを自前で書くとどんな感じになるか?
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
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