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
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to