jeudi 7 février 2019

Python 3.7: Detect name of property being accesed from class

So I am making a Class Which can dynamically return a property depending on whether or not a property was accessed on it. It also detects the name of the property when accessed by a class. my class code is as follows

class ConfigItem(object):
    value: object
    key:str
    default: object
    __name__:str = None
    def __init__(self, default=None):
        self.default: type(default) = default
        self.value = default
        self.key = "default_value"
    def __get__(self, instance, owner):
        if self.key:
            self.value = os.environ.get(self.key,self.default)
        else: 
            self.value = self.default
    def __set_name__(self, owner, name):
        self.__name__ = name
        self.key = name

I want the code to have the following behavior:

when created like this:

a_test_key = ConfigItem('default_value')
a_test_key.key == 'a_test_key' #True

without having to pass the key into the constructor and when accessed as so:

key_value = a_test_key

returns a_test_key.value

but when accessed any other way such as:

a_test_key.default
a_test_key.key

returns the respected values.

I think the solution has to do with the get(self, instance, owner) method, but I am unsure how to detect if a property has been accessed from ConfigItem.

Any takers on how to solve this problem?





Aucun commentaire:

Enregistrer un commentaire