[Python-Dev] namedtuple implementation grumble (original) (raw)

dw+python-dev at hmmz.org dw+python-dev at hmmz.org
Sun Jun 8 23:51:35 CEST 2014


On Sun, Jun 08, 2014 at 05:27:41PM -0400, Eric V. Smith wrote:

How would you write Namedtuple.new?

Knew something must be missing :) Obviously it's possible, but not nearly as efficiently as reusing the argument parsing machinery as in the original implementation.

I guess especially the kwargs implementation below would suck..

_undef = object()

class _NamedTuple(...):
    def __new__(cls, *a, **kw):
        if kw:
            a = list(a) + ([_undef] * (len(self._fields)-len(a)))
            for k, v in kw.iteritems():
                i = cls._name_id_map[k]
                if a[i] is not _undef:
                    raise TypeError(...)
                a[i] = v
            if _undef not in a:
                return tuple.__new__(cls, a)
            raise TypeError(...)
        else:
            if len(a) == len(self._fields):
                return tuple.__new__(cls, a)
            raise TypeError(...)

def namedtuple(name, fields):
    fields = fields.split()
    cls = type(name, (_NamedTuple,), {
        '_fields': fields,
        '_name_id_map': {k: i for i, k in enumerate(fields)}
    })
    for i, field_name in enumerate(fields):
        getter = functools.partial(_NamedTuple.__getitem__, i)
        setattr(cls, field_name, property(getter))
    return cls

David



More information about the Python-Dev mailing list