[Python-ideas] Different interface for namedtuple?
Carl M. Johnson
cmjohnson.mailinglist at gmail.com
Fri Mar 4 09:32:13 CET 2011
For those interested here's a working implementation, minus type
checking but with support for the kwargs of namedtuple:
>>> from collections import namedtuple
>>>
>>> # The custom dictionary
... class member_table:
... def __init__(self):
... self.member_names = []
...
... def __setitem__(self, key, value):
... self.member_names.append(key)
...
... def __getitem__(self, key):
... self.member_names.append(key)
...
>>> # The metaclass
... class TupleNamer(type):
... @classmethod
... def __prepare__(metacls, name, bases, **kwargs):
... return member_table()
...
... def __new__(cls, name, bases, clsdict, **kwargs):
... #So that the MetaClass is inheritable, don't apply
... #to things without a base
... if not bases:
... return type.__new__(cls, name, bases, {})
... #The first two things in member_names are always
... #"__name__" and "__module__", so don't pass those on
... return namedtuple(name, ' '.join(clsdict.member_names[2:]),
**kwargs)...
... def __init__(cls, name, bases, classdict, **kwargs):
... type.__init__(cls, name, bases, classdict)
...
>>> class NamedTuple(metaclass=TupleNamer): pass
...
>>> class Point(NamedTuple, rename=True): x, y, x
...
>>> Point(1, 2, 3)
Point(x=1, y=2, _2=3)
More information about the Python-ideas
mailing list