[Python-ideas] namedtuple() subclasses again

Jan Kaliszewski zuo at chopin.edu.pl
Fri Mar 25 15:06:37 CET 2011


Hello,

Another thoughts (and use cases) about namedtuple-DRY-matter and (what
is more important) subclassing namedtuple() classes:

Quite often I need to create my own named tuple class(es) with some
additional methods or modifications of existing ones (most often: a
custom version of __repr__()). Now I must write something like:

    _MyNamedTupleBase = namedtuple('MyNamedTuple',
                                   ('one_field',
                                    'another_field',
                                    'and_another_one'))

    class MyNamedTuple(_MyNamedTupleBase):
        def __repr__(self):
            "My sophisticated __repr__()"
        # and e.g. some new methods...

...or:

    class MyNamedTuple(namedtuple('MyNamedTuple',
                                  ('one_field',
                                   'another_field',
                                   'and_another_one'))):
        def __repr__(self):
            "My sophisticated __repr__()"
        # and e.g. some new methods...

It would be very nice to be able to do it in such a way:

    class MyNamedTuple(namedtuple.abc):
        _fields = (
            'one_field',
            'another_field',
            'and_another_one',
        )
        def __repr__(self):
            "My sophisticated __repr__()"
        # and e.g. some new methods...

...and especially:

    class MyAbstractNamedTuple(namedtuple.abc):
        def __repr__(self):
            "My sophisticated __repr__()"
        # and e.g. some new methods...
        
    class MyNamedTupleA(MyAbstractNamedTuple):
        _fields = 'a b c'

    class MyNamedTupleB(MyAbstractNamedTuple):
        _fields = (
            'one_field',
            'another_field',
            'and_another_one',
        )

(Please note that _fields is a part of the public API of named tuples).

Implementation would be easy to explain (and to do; actually I have an
outline in my head). The type (metaclass) of namedtuple.abc would be a
subclass of abc.ABCMeta and would also act (by ABC registration
mechanism) as an abstract base for all named tuples and structsequences
like sys.version_info. So all these expressions would be True:

>>> isinstance(namedtuple('Foo', 'x y z'), namedtuple.abc)
>>> isinstance(sys.version_info, namedtuple.abc)

And obviously:

>>> isinstance(MyNamedTuple, namedtuple.abc)  # referiring to the above examples

What do you think about the idea?

Regards.
*j




More information about the Python-ideas mailing list