Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python getattr() with multiple params

Construction getattr(obj, 'attr1.attr2', None) does not work. What are the best practices to replace this construction? Divide that into two getattr statements?

like image 403
Nikita Vstovsky Avatar asked Mar 05 '17 08:03

Nikita Vstovsky


People also ask

How many arguments Getattr () function receives in Python?

getattr() is one of the coolest built-in functions in Python. It takes three arguments: an object. name of the object's attribute but in the string format.

What does Getattr () do in Python?

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

Is Getattr slow python?

The getattr approach is slower than the if approach, reducing an insignificant ~3% the performance if bar is set and a considerable~35% if is not set.

What is Setattr () and Getattr () used for?

Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.


1 Answers

You can use operator.attrgetter() in order to get multiple attributes at once:

from operator import attrgetter

my_attrs = attrgetter(attr1, attr2)(obj)
like image 178
Mazdak Avatar answered Oct 24 '22 18:10

Mazdak