Someplace nice

The Python getattr function

This one confused me for quite a while. After a bit of reading, I understood what the function did. It allows one to fetch an attribute from an object, using a string object or variable instead of an identifier. It basically goes like this:

class Blank: 
  def __init__(self):
    self.test_attr = 1


>>>t = Blank()

>>>t.test_attr
1

>>>t.test_attr_2
Traceback...
AttributeError: Blank instance has no attribute 'test_attr_2'

>>>getattr(t, 'test_attr')
1

>>>getattr(t, 'test_attr_2')
Traceback...
AttributeError: Blank instance has no attribute 'test_attr_2'

This all seemed to make sense, but what I couldn’t work out was why you would bother to use the getattr function when it appeared to give exactly the same results with just a little more typing. The answer, of course, is that you might not know the name of the attribute until runtime, so this can be accessed with a variable assigned when the code is run.

>>>getattr(object, variable_assigned_at_runtime)
Archive