Chained attributes

Question:

Is there a way to make a python class such that,

a = Foo()
a.user.details.money.pay = 130000
print(a.user.details.money.pay)

outputs 130000

If possible, could you also explain the class?

Asked By: Surya

||

Answers:

Python calls __getattr__ when it can’t find an attribute on an object. Your class could use that to assign a new instance of itself to the attribute. Now you have a named attribute that will play the same game for the next attribute down the line.

class Foo:

    def __getattr__(self, name):
        setattr(self, name, foo:=Foo())
        return foo


a = Foo()
a.user.details.money.pay = 130000
print(a.user.details.money.pay)

Here, a.__getattr__ creates user, a.user.__getattr__ creates details, and etc. Since this is an assignment operation, that last component, pay, is a __setattr__ operation, not a __getattr__, so your custom getter doesn’t run.

This can mask bugs as this class will create unintended attributes as well.

Answered By: tdelaney
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.