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

Steven D'Aprano steve at pearwood.info
Sun Feb 17 22:38:38 CET 2013


On 17/02/13 00:46, Jan Kaliszewski wrote:
> 16.02.2013 11:18, Antoine Pitrou wrote:
>> On Sat, 16 Feb 2013 15:51:28 +1100
>> Steven D'Aprano <steve at pearwood.info> wrote:
>>>
>>> from collections import namedtuple
>>>
>>> FIELDNAMES = """...""" # Format it however you like.
>>>
>>> class MyClassWithAnExtremelyLongName(namedtuple("Cheese", FIELDNAMES)):
>>> pass
>>
>> Still not very elegant IMO
>
> I agree. I see some nicer (IMHO) alternatives... Apart from the recipe I mentioned
> in the recent post (although I am *not* convinced it should be added to the stdlib)
> some decorator-based way may be nice, e.g.:
>
> @namedtuple(fields='length weight is_poisonous')
> class Snake:
>     def hiss(self):
>         return 'hiss' + self.length * 's'


This implies that all namedtuples must be callable.

Point3D = namedtuple('Point3D', 'x y z')
pt = Point3D(2, 4, 8)

I don't think it's appropriate for tuples, named or not, to be callable.



-- 
Steven



More information about the Python-ideas mailing list