What does this (simple?) expression in Python mean? func(self)(*args)

Question:

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?

Asked By: rapadura

||

Answers:

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)
Answered By: David Heffernan

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.

Answered By: Sven Marnach

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)
Answered By: phihag

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.

Answered By: g.d.d.c
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.