cammil cammil - 2 years ago 88
Python Question

Why does `getattr` not support consecutive attribute retrievals?

class A(): pass

a = A()
b = A()

a.b = b
b.c = 1

a.b # this is b
getattr(a, "b") # so is this

a.b.c # this is 1
getattr(a, "b.c") # this raises an AttributeError

It seemed very natural to me to assume the latter. I'm sure there is a good reason for this. What is it?

Answer Source

You can't put a period in the getattr function because getattr is a direct dictionary lookup of the object.

If you use the 'dir' function on a, you'll see the dictionary keys that correspond to your object's attributes. In this case, "b.c" isn't in the set of dictionary keys.

The correct way to do this would be:

getattr(getattr(a, "b"), "c")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download