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

Steven D'Aprano steve at pearwood.info
Fri Feb 15 00:17:32 CET 2013


On 15/02/13 09:40, Antoine Pitrou wrote:
> On Fri, 15 Feb 2013 09:09:57 +1100
> Steven D'Aprano<steve at pearwood.info>  wrote:
>
>> 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:
>
> Well, it's perfectly acceptable as long as you have one-letter field
> names. Try with real field names and it becomes rather unwieldy.

Exactly the same thing can be said about the __field__ line. The only difference is that in one case you reach "unwieldy" a little sooner than in the other.

There are well-known ways to deal with excessively long lines of code which don't require a new collection type.


class MyClassWithAnExtremelyLongName(
         collections.namedtuple("Cheese",
          ("cheddar swiss ricotta camembert gouda parmesan brie limburger havarti"
           " danish_blue roquefort greek_feta provolone mozzarella edam maasdam"
           " stilton wensleydale red_leicester american colby monterey_jack kapiti"
           " casu_marzu")
          )
         ):
     pass


Style arguments about the placement of closing brackets to /dev/null :-)


I'm simply not seeing enough benefit to NamedTuple to make up for the invariable confusion between NamedTuple and namedtuple.




-- 
Steven



More information about the Python-ideas mailing list