The Python Oracle

Why should I ever use "getattr()"?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Why Should I Ever Use &Quot;Getattr()&Quot;?
00:17 Answer 1 Score 7
00:35 Answer 2 Score 3
00:56 Accepted Answer Score 5
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/3111...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 7


You can use getattr if you have the name of the attribute as a string. e.g:

attribute = "some_attribute"
getattr(object, attribute)

Also it is nice to use when you have a default value that you want to use when the attribute is not set:

getattr(object, attribute, "default")  # does not raise AttributeError



ACCEPTED ANSWER

Score 5


Objects in Python can have attributes. For example you have an object person, that has several attributes: name, gender, etc. You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc.

But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called gender_attribute_name.

if

attr_name = 'gender'

then, instead of writing

gender = person.gender

you can write

gender = getattr(person, attr_name)

Some practice:

>>> class Person():
...     name = 'Victor'
...     def say(self, what):
...         print(self.name, what)
... 
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello
>>> 



ANSWER 3

Score 3


Usually when the name of the method is not known when you write the code:

def print_some_attr(obj, attr):
    print getattr(obj, attr)

Or when you want to write generic code that works on multiple attributes, while avoiding writing the same thing over and over:

for attr in ["attr1", "attr2", "attr3"]:
    print "%s is: %s" % (attr, getattr(obj, attr))