Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `getattr` not support consecutive attribute retrievals?

Tags:

python

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?

like image 901
cammil Avatar asked Aug 15 '12 19:08

cammil


People also ask

What is the difference between Getattribute and Getattr?

getattribute: Is used to retrieve an attribute from an instance. It captures every attempt to access an instance attribute by using dot notation or getattr() built-in function. getattr: Is executed as the last resource when attribute is not found in an object.

What is the purpose of Getattr () method in python?

The getattr() function returns the value of the specified attribute from the specified object.

What is Getattr () used for * What is Getattr () used for to delete an attribute to check if an attribute exists or not to set an attribute?

What is getattr() used for? Explanation: getattr(obj,name) is used to get the attribute of an object. 6.

What is the point of Getattr?

Python | getattr() method Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.


1 Answers

You can't put a period in the getattr function because getattr is like accessing the dictionary lookup of the object (but is a little bit more complex than that, due to subclassing and other Python implementation details).

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

The only way to do this with getattr is to nest calls:

getattr(getattr(a, "b"), "c") 

Luckily, the standard library has a better solution!

import operator operator.attrgetter("b.c")(a) 
like image 178
Thane Brimhall Avatar answered Sep 23 '22 01:09

Thane Brimhall