Movatterモバイル変換
[0]ホーム
[Python-Dev] namedtuple implementation grumble
dw+python-dev at hmmz.orgdw+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 notnearly as efficiently as reusing the argument parsing machinery as inthe 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 clsDavid
More information about the Python-Devmailing list
[8]ページ先頭