Skip to content

Instantly share code, notes, and snippets.

@thiagoa
Created February 22, 2016 14:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save thiagoa/7f08519d3bdf17d21869 to your computer and use it in GitHub Desktop.
Python: My simple ContextManager implementation
import time
class ContextManager():
def __init__(self, generator_method, args, kwargs):
self.generator_method = generator_method
self.args = args
self.kwargs = kwargs
def __enter__(self):
self.generator = self.__run_generator()
next(self.generator)
def __exit__(self, *_):
for _ in self.generator:
pass
def __run_generator(self):
return self.generator_method(*self.args, **self.kwargs)
def context_manager(generator_method):
def method_with_context(*args, **kwargs):
return ContextManager(generator_method, args, kwargs)
return method_with_context
@context_manager
def measure(task_name):
t = time.time()
yield
print(task_name, 'took', time.time() - t, 'seconds.')
with measure('sleep test') as method:
time.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment