2

I am working with a code base which contains a line which I really can't understand:

x, x, z = getattr(ReceiveFile, maxsizes)(input, args)

So if it didn't have the second tuple at the end it would be just

x, y, z = ReceiveFile.maxsizes

How do I interpret that tuple at the end (input, args) ? I can't that easily run this code and play with a debugger to come to an understanding..

cardamom
  • 6,873
  • 11
  • 48
  • 102

2 Answers2

4

Given a string value for the maxsizes variable:

maxsizes = "abc"

the following

x, x, z = getattr(ReceiveFile, maxsizes)(input, args)

is equivalent to:

x, x, z = ReceiveFile.abc(input, args)

Or in words: The object ReceiveFile has a method with the name maxsizes (which is ReceiveFile.abc) which is called with the arguments input and args. The parentheses do not denote a tuple, but a function call.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • hello, `maxsizes` is a method or an attirubute of the `ReceiveFile?. [link](https://docs.python.org/2/library/functions.html#getattr) or when we add a `(input, args)`, it interpreted as method? Thanks – Aybars Dec 19 '18 at 13:43
  • @Aybars First of all, a method is an attribute. And `maxsizes` is the name of a method of `ReceiveFile`. Note that `maxsizes` is a variable, so that name is not necessarily `"maxsizes"`, but can be any eligible string really. – user2390182 Dec 19 '18 at 13:46
  • Thanks for your reply. – Aybars Dec 19 '18 at 13:47
  • @Aybars Cheers. There is no interpretation involved: first the attribute (without `()`) is looked up and an object returned. That object is then called via `(...)`. This either works or raises a TypeError, if the object is not callable. – user2390182 Dec 19 '18 at 13:50
3

getattr is returning a function, which is then called with input and args as its arguments. The return value of that function is then unpacked into x, y, and z.

In longer form, it's the same as

f = getattr(ReceiveFile, maxsizes)
x, y, z = f(input, args)
chepner
  • 497,756
  • 71
  • 530
  • 681