[Python-ideas] A subclassing API for named tuples?

Steven D'Aprano steve at pearwood.info
Thu Feb 14 23:09:57 CET 2013


On 15/02/13 00:19, Nick Coghlan wrote:
> An exchange with Antoine in one of the enum threads sparked a thought.
>
> A recurring suggestion for collections.namedtuple is that it would be
> nice to be able to define them like this (as it not only avoids having
> to repeat the class name, but also allows them to play nicely with
> pickle and other name-based reference mechanisms):
>
>      class MyTuple(collections.NamedTuple):
>          __fields__ = "a b c d e".split()


How would that differ from this?

class MyTuple(collections.namedtuple("MyTupleParent", "a b c d e")):
     pass


Apart from the DRY violation in the class name, I find that perfectly
acceptable, and it seems to work fine with pickling:


py> t = MyTuple(2, 4, 8, 16, 32)
py> t
MyTuple(a=2, b=4, c=8, d=16, e=32)
py> s = pickle.dumps(t)
py> u = pickle.loads(s)
py> u == t
True




-- 
Steven



More information about the Python-ideas mailing list