10

What is the use of typename associated with a particular class? For example,

Point = namedtuple('P', ['x', 'y'])

Where would you normally use typename 'P'?

Thank you!

Sagar Patel
  • 187
  • 1
  • 10
  • possible duplicate of [What are "named tuples" in Python?](http://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python) – b4hand Dec 05 '14 at 01:25

1 Answers1

15

Just for sanity's sake, the first argument to namedtuple should be the same as the variable name you assign it to:

>>> from collections import namedtuple
>>> Point = namedtuple('P','x y')
>>> pp = Point(1,2)
>>> type(pp)
<class '__main__.P'>

isinstance isn't too concerned about this, although just what is 'P' is not known:

>>> isinstance(pp,Point)
True
>>> isinstance(pp,P)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'P' is not defined

But pickle is one module that cares about finding the classname that matches the typename:

>>> import pickle
>>> ppp = pickle.dumps(pp)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python26\lib\pickle.py", line 1366, in dumps
    Pickler(file, protocol).dump(obj)
  File "c:\python26\lib\pickle.py", line 224, in dump
    self.save(obj)
  File "c:\python26\lib\pickle.py", line 331, in save
    self.save_reduce(obj=obj, *rv)
  File "c:\python26\lib\pickle.py", line 401, in save_reduce
    save(args)
  File "c:\python26\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "c:\python26\lib\pickle.py", line 562, in save_tuple
    save(element)
  File "c:\python26\lib\pickle.py", line 286, in save
    f(self, obj) # Call unbound method with explicit self
  File "c:\python26\lib\pickle.py", line 748, in save_global
    (obj, module, name))
pickle.PicklingError: Can't pickle <class '__main__.P'>: it's not found as __main__.P

If I define the namedtuple as 'Point', then pickle is happy:

>>> Point = namedtuple('Point','x y')
>>> pp = Point(1,2)
>>> ppp = pickle.dumps(pp)
>>>

Unfortunately, it is up to you to manage this consistency. There is no way for namedtuple to know what you are assigning its output to, since assignment is a statement and not an operator in Python, so you have to pass the correct classname into namedtuple, and assign the resulting class to a variable of the same name.

PaulMcG
  • 62,419
  • 16
  • 94
  • 130
  • 1
    you don't need the `.split()` on the field names, that's [done automatically](http://docs.python.org/library/collections#collections.namedtuple) if you specify the names as a string. otherwise +1 – mata May 07 '12 at 13:11
  • Ah, thanks! I haven't used namedtuple in a while, was just mimicking the OP's format. I do something very similar in pyparsing's `oneOf` function. – PaulMcG May 07 '12 at 13:14
  • 3
    There's also the default `repr`: you want `Point(x=1, y=2)`, not `P(x=1, y=2)`. – Chris Morgan May 07 '12 at 14:46