Issue 6722: collections.namedtuple: confusing example (original) (raw)

Maybe it's just me, but it took me several attempts to understand namedtuple example in the documentation 1. The problem is that the first example uses verbose=True. It's very unusual to get Python source as the output in Python shell. At first I thought there's some syntax error in documentation source.

I know that several lines above one can read: "If verbose is true, the class definition is printed just before being built." But during first several attempts to understand namedtuple, I skipped it and directly scrolled to the first example.

I think the first example on namedtuple usage shouldn't use verbose=True.

You could argue I had to try using namedtuple inside Python shell. I agree. But unfortunately Python 2.6 was not installed on the computer I was at.

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] + p1 # 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)' slots = () _fields = ('x', 'y') def new(_cls, x, y): return _tuple.new(_cls, (x, y)) @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 def repr(self): return 'Point(x=%r, y=%r)' % self def _asdict(t): 'Return a new dict which maps field names to their values' return {'x': t[0], 'y': t1} 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 def getnewargs(self): return tuple(self) x = _property(_itemgetter(0)) y = _property(_itemgetter(1))

In fact, thanks to the person (Alexey Shamrin) who created this issue (issue found while googling for "namedtuple"), I have understood the namedtuple example in the documentation. I think like him the verbose=True example that cames first is very confusing.

(BTW I must say that the Python reference documentation is usually excellent, so my expectations are high!)