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

The Python documentation says:

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

and he gives an example

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

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

While experimenting, it seems that the argument does not matter:

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

What is the difference? How does typename argument matter?

+6
source share
1 answer

When executing the following code:

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

you:

  • creating a new type named Foo ;
  • assigning this type to a variable named Bar .

This 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 will see the difference when printing a class or instance:

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

You may ask why namedtuple requires a type name as it is redundant (with the usual convention). Well, namedtuple creates the type before assigning the variable, so it cannot infer the type name, and it should be told explicitly. (Or better: he could print the name by checking the code of the caller, but that one is hacked and will not work for non-standard cases.)

+8
source

All Articles