Where should I define namedtuple classes in Python - what namespace?

Namedtuples are useful in Python for small datasets.

Take for example this namedtuple:

import collections
sesameEpisodeNTC = collections.namedtuple('sesameEpisodeNTC', 
                                          'lead_character', 'has_elmo')
se0 = sesameEpisodeNTC(lead_character='bigbird', has_elmo=False)

Can a class definition ('sesameEpisodeNTC =' ...) be an attribute of another class? I would prefer to keep some namedtuples inside classes to avoid cluttering the module namespace. But this causes problems with pickling (cPickle, dill), which is showstopper.

Similarly, I noticed the first parameter for the definition of the namedtuple class, the type name (that is, "sesameEpisodeNTC") must be the name of the class, otherwise the etching does not work. (using both 2.7 and 3.4). This duplication is not ideal. Are there other methods for the typename parameter and does this affect the code besides the etching code?

Are there other unprovable corner cases missing from namedtuples? It's annoying that some of the most useful python data structures have sharp corners that can get caught in parts of stdlib.

+4
source share
1 answer

namedtuple , dill namedtuple . , " ". , . namedtuple .

>>> import collections
>>> nt = collections.namedtuple('nt',['one','two'])
>>> nt
<class '__main__.nt'>
>>> 
>>> import dill
>>> 
>>> dill.copy(nt)
<class '__main__.nt'>
>>> 
>>> class Foo(object):
...   cnt = nt
... 
>>> f = Foo()
>>> f.cnt
<class '__main__.nt'>
>>> f.cnt(1,2)
nt(one=1, two=2)
>>> 
>>> dill.copy(f)
<__main__.Foo object at 0x10f1b5850>
>>> dill.copy(Foo)
<class '__main__.Foo'>
>>> 

/ dill github, , - namedtuples - , , namedtuple.

0

All Articles