11

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!

1

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

3 Comments

you don't need the .split() on the field names, that's done automatically if you specify the names as a string. otherwise +1
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.
There's also the default repr: you want Point(x=1, y=2), not P(x=1, y=2).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.