diff options
| author | Raymond Hettinger <python@rcn.com> | 2008-01-05 01:35:43 (GMT) | 
|---|---|---|
| committer | Raymond Hettinger <python@rcn.com> | 2008-01-05 01:35:43 (GMT) | 
| commit | 02740f73ff0f12d276ef16b73208d4f9f8d62baa (patch) | |
| tree | 7165cccdbee9448c4a0474ac4d85c0427b7367b4 /Lib/collections.py | |
| parent | ced4eb06e4fe528c99b34f4167011f8908c933af (diff) | |
| download | cpython-02740f73ff0f12d276ef16b73208d4f9f8d62baa.zip cpython-02740f73ff0f12d276ef16b73208d4f9f8d62baa.tar.gz cpython-02740f73ff0f12d276ef16b73208d4f9f8d62baa.tar.bz2  | |
Improve namedtuple's _cast() method with a docstring, new name, and error-checking.
Diffstat (limited to 'Lib/collections.py')
| -rw-r--r-- | Lib/collections.py | 11 | 
1 files changed, 9 insertions, 2 deletions
diff --git a/Lib/collections.py b/Lib/collections.py index 487b119..2a58b86 100644 --- a/Lib/collections.py +++ b/Lib/collections.py @@ -54,6 +54,7 @@ def namedtuple(typename, field_names, verbose=False):          seen_names.add(name)      # Create and fill-in the class template +    numfields = len(field_names)      argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes      reprtxt = ', '.join('%s=%%r' % name for name in field_names)      dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names)) @@ -63,7 +64,13 @@ def namedtuple(typename, field_names, verbose=False):          _fields = %(field_names)r \n          def __new__(cls, %(argtxt)s):              return tuple.__new__(cls, (%(argtxt)s)) \n -        _cast = classmethod(tuple.__new__) \n +        @classmethod +        def _make(cls, iterable): +            'Make a new %(typename)s object from a sequence or iterable' +            result = tuple.__new__(cls, iterable) +            if len(result) != %(numfields)d: +                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) +            return result \n          def __repr__(self):              return '%(typename)s(%(reprtxt)s)' %% self \n          def _asdict(t): @@ -71,7 +78,7 @@ def namedtuple(typename, field_names, verbose=False):              return {%(dicttxt)s} \n          def _replace(self, **kwds):              'Return a new %(typename)s object replacing specified fields with new values' -            return self.__class__._cast(map(kwds.get, %(field_names)r, self)) \n\n''' % locals() +            return self.__class__._make(map(kwds.get, %(field_names)r, self)) \n\n''' % locals()      for i, name in enumerate(field_names):          template += '        %s = property(itemgetter(%d))\n' % (name, i)      if verbose:  | 
