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?
When you execute the following code:
Bar = collections.namedtuple('Foo', 'field')
you are:
Foo
;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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With