Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between namedtuple return and its typename argument?

Tags:

python

Python documentation says:

collections.namedtuple(typename, field_names[, verbose=False][, rename=False])
Returns a new tuple subclass named typename. 

and it gives an example

>>>Point = namedtuple('Point',...

In all the examples I could find, the return from namedtuple and argument typename are spelled the same.

Experimenting, it seems the argument does not matter:

>>>Class = collections.namedtuple('Junk', 'field')
>>>obj = Class(field=1)
>>>print obj.field
1

What is the distinction? How does the typename argument matter?

like image 862
Mark Galeck Avatar asked Jan 23 '16 10:01

Mark Galeck


1 Answers

When you execute the following code:

Bar = collections.namedtuple('Foo', 'field')

you are:

  1. creating a new type named Foo;
  2. assigning that type to a variable named Bar.

That code is equivalent to this:

class Foo:
    ...

Bar = Foo
del Foo

Even if you assign your class to a variable with a different name, Foo will still be the "official" name, that is: Bar.__name__ will still be 'Foo'.

You'll see the difference when you print either the class or the instance:

>>> Bar = collections.namedtuple('Foo', 'field')
>>> obj = Bar(field=1)
>>> obj
Foo(field=1)

You may ask why namedtuple requires the type name, as it is redundant (with the usual convention). Well, namedtuple builds the type before the variable is assigned, so it cannot infer the type name and it needs to be told explicitly. (Or better: it could infer the name by inspecting the code of the caller, but that's hackish and won't work for non conventional cases.)

like image 102
Andrea Corbellini Avatar answered Sep 22 '22 06:09

Andrea Corbellini