Skip to content

Instantly share code, notes, and snippets.

@briggleman
Created October 26, 2017 17:59
Show Gist options
  • Save briggleman/7c63bd036691d6c593ba84d536df6012 to your computer and use it in GitHub Desktop.
Save briggleman/7c63bd036691d6c593ba84d536df6012 to your computer and use it in GitHub Desktop.
An example of using the contextlib ContextDecorator class to create a class that can be used as a decorator or a context manager
import time
from contextlib import ContextDecorator
class Logger(ContextDecorator):
"""
Logger()
Logger can be used as both a decorator or as a context manager.
Examples:
As a decorator:
import logger
@logger
def somefunc():
return "hello world!"
As a context manager:
import logger
def somefunc():
with logger:
print("context managed!")
"""
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("runtime: {}".format(time.time() - self.start))
return False
logger = Logger()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment