I saw some Python code like: getattr(self, that)(*args)
. what does it mean? I see that the builtin getattr
function gets called, passing the current object and that
; but what is the (*args)
doing after that? Does it call something with *args
as parameter?

- 62,466
- 11
- 102
- 153

- 5,242
- 7
- 39
- 57
4 Answers
It calls the value returned by getattr(self, that)
with the arguments specified in the array args
.
For example, assuming that = 'thatFunction'
and args = [1,2,3]
, it's the same as
self.thatFunction(1, 2, 3)

- 278,196
- 72
- 453
- 469
You're right on track. that
is going to be the name of a method on the object. getattr()
is returning that method (function) and then calling it. Because functions are first class members they can be passed around, returned, etc.

- 46,865
- 9
- 101
- 111
It calls the method of self whose name is held in that
and passing *args
as the arguments to the function. args
is a tuple and *args
is special syntax that allows you to call a function and expand a tuple into a list of arguments.
Suppose that that
contained the string 'f'
, and args
was (1,2,3)
, then getattr(self, that)(*args)
would be equivalent to:
self.f(1, 2, 3)

- 601,492
- 42
- 1,072
- 1,490
getattr()
fetches the attribute of self
named by the string variable that
. The return value, i.e. the attribute named by that
, is then called with the arguments given by the iterable args
.
Assuming that
has the value "foo"
, the following four lines are equivalent:
self.foo(*args)
f = self.foo; f(*args)
f = getattr(self, that); f(*args)
getattr(self, that)(*args)
Using *args
as parameter is the same as using all of the items in args
as spearate parameters.

- 574,206
- 118
- 941
- 841