Created
October 26, 2017 17:59
-
-
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
This file contains hidden or 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
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