Last active
December 22, 2017 02:41
-
-
Save xuanyu-h/95a30b613c7471dcc06c7fcde1045aea to your computer and use it in GitHub Desktop.
python context??
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
from functools import wraps | |
def print_method_name(f): | |
@wraps(f) | |
def decorated(*args, **kwargs): | |
print("enter function: {0}, {1}, {2}".format(f.__name__, args, kwargs)) | |
return f(*args, **kwargs) | |
return decorated | |
class Settings(object): | |
_singleton = {} | |
# attributes with defaults | |
__attrs__ = ('timeout', 'verbose') | |
@print_method_name | |
def __init__(self, **kwargs): | |
super(Settings, self).__init__() | |
self.__dict__ = self._singleton | |
@print_method_name | |
def __call__(self, *args, **kwargs): | |
# new instance of class to call | |
r = self.__class__() | |
# cache previous settings for __exit__ | |
r.__cache = self.__dict__.copy() | |
map(self.__cache.setdefault, self.__attrs__) | |
# set new settings | |
self.__dict__.update(*args, **kwargs) | |
return r | |
@print_method_name | |
def __enter__(self): | |
pass | |
@print_method_name | |
def __exit__(self, *args): | |
# restore cached copy | |
self.__dict__.update(self.__cache.copy()) | |
del self.__cache | |
@print_method_name | |
def __getattribute__(self, key): | |
if key in object.__getattribute__(self, '__attrs__'): | |
try: | |
return object.__getattribute__(self, key) | |
except AttributeError: | |
return None | |
return object.__getattribute__(self, key) | |
settings = Settings() |
Author
xuanyu-h
commented
Dec 22, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment