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.)
source share