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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4