When to use __getattr__
python
Solution
One example is to use object notation with dictionaries. For example, consider a dictionary
myDict = {'value': 1}
Typically in Python one accesses the 'value' variable as
myDict['value']
which will print `1` at the Python interpreter. However, one may wish to use the `myDict.value` notation. This may be achieved by using the following class:
class DictAsMember(dict):
def __getattr__(self, name):
value = self[name]
if isinstance(value, dict):
value = DictAsMember(value)
return value
my_dict = DictAsMember()
my_dict['property'] = {'sub_property': 1}
print(my_dict.property.sub_property) # 1 will be printed
Problem
I came across the `__getattr__` built-in and was wondering when it would be used. I had a hard time thinking of a practical use from the documentation http://docs.python.org/reference/datamodel.html#. What would be an actual example of how it could be used and useful in code?