Created
October 30, 2016 17:58
-
-
Save KyleJamesWalker/847b271a8a86c908c387243d7b5ccb43 to your computer and use it in GitHub Desktop.
Simple Example of a class with decorator support, context manager support
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
class DecoratedContextManager: | |
def __init__(self): | |
pass | |
def start(self): | |
"""Starts, for example opens file. | |
""" | |
pass | |
def stop(self): | |
"""Stops, example closes file. | |
""" | |
pass | |
def __enter__(self): | |
"""Context manager support | |
""" | |
self.start() | |
return self | |
def __exit__(self, exception_type, exception_value, traceback): | |
"""Context manager support | |
""" | |
self.stop() | |
def __del__(self): | |
"""Restore original settings if object looses scope. | |
""" | |
self.stop() | |
def __call__(self, org_func): | |
"""Decorator Support | |
""" | |
@functools.wraps(org_func) | |
def wrapper(*args, **kwargs): # pylint: disable=C0111 | |
try: | |
self.start() | |
return org_func(*args, **kwargs) | |
finally: | |
self.stop() | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment