[issue6722] collections.namedtuple: confusing example
Alexey Shamrin
report at bugs.python.org
Thu Aug 20 13:13:07 CEST 2009
Alexey Shamrin <shamrin at gmail.com> added the comment:
Raymond, sorry if I wasn't clear. I'm fine with the API (haven't used it
yet though, because I was stuck after skimming through its documentation).
I suggest to make *first* example simple (without verbose=True) and to
move an example with verbose=True little furthere. I think it should be
something like this:
Example:
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> Point = namedtuple('Point', 'x y')
>>> p = Point(11, y=22) # instantiate with positional or keyword
arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)
>>> namedtuple('Point', 'x y', verbose=True) # print class definition
class Point(tuple):
'Point(x, y)'
<BLANKLINE>
__slots__ = ()
<BLANKLINE>
_fields = ('x', 'y')
<BLANKLINE>
def __new__(_cls, x, y):
return _tuple.__new__(_cls, (x, y))
<BLANKLINE>
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Point object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' %
len(result))
return result
<BLANKLINE>
def __repr__(self):
return 'Point(x=%r, y=%r)' % self
<BLANKLINE>
def _asdict(t):
'Return a new dict which maps field names to their values'
return {'x': t[0], 'y': t[1]}
<BLANKLINE>
def _replace(_self, **kwds):
'Return a new Point object replacing specified fields
with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' %
kwds.keys())
return result
<BLANKLINE>
def __getnewargs__(self):
return tuple(self)
<BLANKLINE>
x = _property(_itemgetter(0))
y = _property(_itemgetter(1))
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6722>
_______________________________________
More information about the Python-bugs-list
mailing list