Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of class typenames in python

Tags:

python

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!

like image 230
Sagar Patel Avatar asked May 07 '12 12:05

Sagar Patel


1 Answers

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.

like image 114
PaulMcG Avatar answered Nov 17 '22 08:11

PaulMcG