Created
March 5, 2020 11:52
-
-
Save eirenik0/ccdcae9a876413163a3268ffb456084a to your computer and use it in GitHub Desktop.
Adds to decorated class __getter__ and __setter__ methods that allow to access attributes from proxy_object in the parent class
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 inspect | |
def proxy_to(proxy_obj_name, fields): | |
# type: (Text, List[Text]) -> Callable | |
""" | |
Adds to decorated class __getter__ and __setter__ methods that allow to access | |
attributes from proxy_object in the parent class | |
:param proxy_obj_name: The name of the proxy object that has decorated class. | |
:param fields: | |
Fields which should be accessible in parent object from the proxy object. | |
""" | |
def __getattr__(self, name): | |
if name in fields: | |
proxy_obj = getattr(self, proxy_obj_name) | |
return getattr(proxy_obj, name) | |
module_with_class = "{}::{}".format( | |
inspect.getfile(self.__class__), self.__class__.__name__ | |
) | |
raise AttributeError("{} has not attr `{}`".format(module_with_class, name)) | |
def __setattr__(self, key, value): | |
if key in fields: | |
proxy_obj = getattr(self, proxy_obj_name) | |
setattr(proxy_obj, key, value) | |
else: | |
super(self.__class__, self).__setattr__(key, value) | |
def dec(cls): | |
cls.__getattr__ = __getattr__ | |
cls.__setattr__ = __setattr__ | |
return cls | |
return dec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment