Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 25bb783

Browse files
committed
Merged revisions 59883-59920 via svnmerge from
svn+ssh://[email protected]/python/trunk ........ r59887 | neal.norwitz | 2008-01-10 06:42:58 +0100 (Thu, 10 Jan 2008) | 1 line Reword entry, not sure I made it much better though. ........ r59888 | andrew.kuchling | 2008-01-10 14:37:12 +0100 (Thu, 10 Jan 2008) | 1 line Check for fd of -1 to save fsync() and fstat() call ........ r59891 | thomas.heller | 2008-01-10 19:45:40 +0100 (Thu, 10 Jan 2008) | 1 line Reflow a paragraph, and fix a typo. ........ r59892 | raymond.hettinger | 2008-01-10 20:15:10 +0100 (Thu, 10 Jan 2008) | 1 line Examples for named tuple subclassing should include __slots__ ........ r59895 | raymond.hettinger | 2008-01-10 21:37:12 +0100 (Thu, 10 Jan 2008) | 1 line Clarify how to add a field to a named tuple. ........ r59896 | amaury.forgeotdarc | 2008-01-10 22:59:42 +0100 (Thu, 10 Jan 2008) | 12 lines Closing issue1761. Surprising behaviour of the "$" regexp: it matches the end of the string, AND just before the newline at the end of the string:: re.sub('$', '#', 'foo\n') == 'foo#\n#' Python is consistent with Perl and the pcre library, so we just document it. Guido prefers "\Z" to match only the end of the string. ........ r59898 | raymond.hettinger | 2008-01-11 00:00:01 +0100 (Fri, 11 Jan 2008) | 1 line Neaten-up the named tuple docs ........ r59900 | raymond.hettinger | 2008-01-11 01:23:13 +0100 (Fri, 11 Jan 2008) | 1 line Run doctests on the collections module ........ r59903 | raymond.hettinger | 2008-01-11 02:25:54 +0100 (Fri, 11 Jan 2008) | 1 line Doctest results return a named tuple for readability ........ r59904 | raymond.hettinger | 2008-01-11 03:12:33 +0100 (Fri, 11 Jan 2008) | 1 line Comment-out missing constant (from rev 59819) ........ r59905 | raymond.hettinger | 2008-01-11 03:24:13 +0100 (Fri, 11 Jan 2008) | 1 line Have Decimal.as_tuple return a named tuple. ........ r59906 | raymond.hettinger | 2008-01-11 04:04:50 +0100 (Fri, 11 Jan 2008) | 1 line Let most inspect functions return named tuples ........ r59907 | raymond.hettinger | 2008-01-11 04:20:54 +0100 (Fri, 11 Jan 2008) | 1 line Improve usability of the SequenceMatcher by returning named tuples describing match ranges. ........ r59909 | thomas.heller | 2008-01-11 09:04:03 +0100 (Fri, 11 Jan 2008) | 1 line Add an important missing blank. ........ r59910 | georg.brandl | 2008-01-11 10:19:11 +0100 (Fri, 11 Jan 2008) | 2 lines Guard definition of TIPC_SUB_CANCEL with an #ifdef. ........ r59911 | georg.brandl | 2008-01-11 10:20:58 +0100 (Fri, 11 Jan 2008) | 2 lines News entries for rev. 5990[567]. ........ r59912 | georg.brandl | 2008-01-11 10:55:53 +0100 (Fri, 11 Jan 2008) | 2 lines Documentation for r5990[3567]. ........ r59913 | thomas.heller | 2008-01-11 13:41:39 +0100 (Fri, 11 Jan 2008) | 4 lines The sqlite3 dll, when compiled in debug mode, must be linked with /MDd to use the debug runtime library. Further, the dll will be named sqlite3_d.dll. ........ r59919 | thomas.heller | 2008-01-11 16:38:46 +0100 (Fri, 11 Jan 2008) | 6 lines Revert revision 59913, because it was wrong: The sqlite3 dll, when compiled in debug mode, must be linked with /MDd to use the debug runtime library. Further, the dll will be named sqlite3_d.dll. ........ r59920 | christian.heimes | 2008-01-11 16:42:29 +0100 (Fri, 11 Jan 2008) | 1 line Removed unused variable ........
1 parent 222e127 commit 25bb783

20 files changed

Lines changed: 203 additions & 125 deletions

Doc/glossary.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,13 @@ Glossary
327327
mutable
328328
Mutable objects can change their value but keep their :func:`id`. See
329329
also :term:`immutable`.
330+
331+
named tuple
332+
A tuple subclass whose elements also are accessible as attributes via
333+
fixed names (the class name and field names are indicated in the
334+
individual documentation of a named tuple type, like ``TestResults(failed,
335+
attempted)``). Named tuple classes are created by
336+
:func:`collections.namedtuple`.
330337

331338
namespace
332339
The place where a variable is stored. Namespaces are implemented as

Doc/library/collections.rst

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -397,16 +397,16 @@ they add the ability to access fields by name instead of position index.
397397
method which lists the tuple contents in a ``name=value`` format.
398398

399399
The *fieldnames* are a single string with each fieldname separated by whitespace
400-
and/or commas (for example 'x y' or 'x, y'). Alternatively, *fieldnames*
401-
can be a sequence of strings (such as ['x', 'y']).
400+
and/or commas, for example ``'x y'`` or ``'x, y'``. Alternatively, *fieldnames*
401+
can be a sequence of strings such as ``['x', 'y']``.
402402

403403
Any valid Python identifier may be used for a fieldname except for names
404404
starting with an underscore. Valid identifiers consist of letters, digits,
405405
and underscores but do not start with a digit or underscore and cannot be
406406
a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
407407
or *raise*.
408408

409-
If *verbose* is true, will print the class definition.
409+
If *verbose* is true, the class definition is printed just before being built.
410410

411411
Named tuple instances do not have per-instance dictionaries, so they are
412412
lightweight and require no more memory than regular tuples.
@@ -533,7 +533,7 @@ function::
533533
>>> getattr(p, 'x')
534534
11
535535

536-
To cast a dictionary to a named tuple, use the double-star-operator [#]_::
536+
To convert a dictionary to a named tuple, use the double-star-operator [#]_::
537537

538538
>>> d = {'x': 11, 'y': 22}
539539
>>> Point(**d)
@@ -544,23 +544,24 @@ functionality with a subclass. Here is how to add a calculated field and
544544
a fixed-width print format::
545545

546546
>>> class Point(namedtuple('Point', 'x y')):
547+
... __slots__ = ()
547548
... @property
548549
... def hypot(self):
549550
... return (self.x ** 2 + self.y ** 2) ** 0.5
550551
... def __str__(self):
551-
... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
552+
... return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
552553

553-
>>> for p in Point(3,4), Point(14,5), Point(9./7,6):
554+
>>> for p in Point(3, 4), Point(14, 5/7.):
554555
... print(p)
555556

556-
Point: x= 3.000 y= 4.000 hypot= 5.000
557-
Point: x=14.000 y= 5.000 hypot=14.866
558-
Point: x= 1.286 y= 6.000 hypot= 6.136
557+
Point: x= 3.000 y= 4.000 hypot= 5.000
558+
Point: x=14.000 y= 0.714 hypot=14.018
559559

560560
Another use for subclassing is to replace performance critcal methods with
561-
faster versions that bypass error-checking and that localize variable access::
561+
faster versions that bypass error-checking::
562562

563563
class Point(namedtuple('Point', 'x y')):
564+
__slots__ = ()
564565
_make = classmethod(tuple.__new__)
565566
def _replace(self, _map=map, **kwds):
566567
return self._make(_map(kwds.get, ('x', 'y'), self))
@@ -569,7 +570,7 @@ faster versions that bypass error-checking and that localize variable access::
569570
Subclassing is not useful for adding new, stored fields. Instead, simply
570571
create a new named tuple type from the :attr:`_fields` attribute::
571572

572-
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
573+
>>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
573574

574575
Default values can be implemented by using :meth:`_replace` to
575576
customize a prototype instance::

Doc/library/decimal.rst

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,11 @@ also have a number of specialized methods:
328328

329329
.. method:: Decimal.as_tuple()
330330

331-
Return a tuple representation of the number: ``(sign, digit_tuple, exponent)``.
331+
Return a :term:`named tuple` representation of the number:
332+
``DecimalTuple(sign, digits, exponent)``.
333+
334+
.. versionchanged:: 2.6
335+
Use a named tuple.
332336

333337

334338
.. method:: Decimal.canonical()

Doc/library/difflib.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
336336

337337
Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
338338

339-
If *isjunk* was omitted or ``None``, :meth:`get_longest_match` returns ``(i, j,
339+
If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns ``(i, j,
340340
k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo <= i <= i+k <=
341341
ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', k')`` meeting those
342342
conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i ==
@@ -365,6 +365,9 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
365365

366366
If no blocks match, this returns ``(alo, blo, 0)``.
367367

368+
.. versionchanged:: 2.6
369+
This method returns a :term:`named tuple` ``Match(a, b, size)``.
370+
368371

369372
.. method:: SequenceMatcher.get_matching_blocks()
370373

Doc/library/doctest.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1436,11 +1436,14 @@ DocTestRunner objects
14361436
.. method:: DocTestRunner.summarize([verbose])
14371437

14381438
Print a summary of all the test cases that have been run by this DocTestRunner,
1439-
and return a tuple ``(failure_count, test_count)``.
1439+
and return a :term:`named tuple` ``TestResults(failed, attempted)``.
14401440

14411441
The optional *verbose* argument controls how detailed the summary is. If the
14421442
verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used.
14431443

1444+
.. versionchanged:: 2.6
1445+
Use a named tuple.
1446+
14441447

14451448
.. _doctest-outputchecker:
14461449

Doc/library/inspect.rst

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,8 @@ attributes:
188188

189189
.. function:: getmoduleinfo(path)
190190

191-
Return a tuple of values that describe how Python will interpret the file
191+
Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
192+
module_type)`` of values that describe how Python will interpret the file
192193
identified by *path* if it is a module, or ``None`` if it would not be
193194
identified as a module. The return tuple is ``(name, suffix, mode, mtype)``,
194195
where *name* is the name of the module without the name of any enclosing
@@ -377,8 +378,9 @@ Classes and functions
377378

378379
.. function:: getargspec(func)
379380

380-
Get the names and default values of a function's arguments. A tuple of four
381-
things is returned: ``(args, varargs, varkw, defaults)``. *args* is a list of
381+
Get the names and default values of a function's arguments. A
382+
:term:`named tuple` ``ArgSpec(args, varargs, keywords,
383+
defaults)`` is returned. *args* is a list of
382384
the argument names. *varargs* and *varkw* are the names of the ``*`` and
383385
``**`` arguments or ``None``. *defaults* is a tuple of default argument
384386
values or None if there are no default arguments; if this tuple has *n*
@@ -391,10 +393,10 @@ Classes and functions
391393

392394
.. function:: getfullargspec(func)
393395

394-
Get the names and default values of a function's arguments. A tuple of seven
395-
things is returned:
396+
Get the names and default values of a function's arguments. A :term:`named tuple`
397+
is returned:
396398

397-
``(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)``
399+
``FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)``
398400

399401
*args* is a list of the argument names. *varargs* and *varkw* are the names
400402
of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of
@@ -408,8 +410,8 @@ Classes and functions
408410

409411
.. function:: getargvalues(frame)
410412

411-
Get information about arguments passed into a particular frame. A tuple of four
412-
things is returned: ``(args, varargs, varkw, locals)``. *args* is a list of the
413+
Get information about arguments passed into a particular frame. A :term:`named tuple`
414+
``ArgInfo(args, varargs, keywords, locals)`` is returned. *args* is a list of the
413415
argument names (it may contain nested lists). *varargs* and *varkw* are the
414416
names of the ``*`` and ``**`` arguments or ``None``. *locals* is the locals
415417
dictionary of the given frame.
@@ -476,8 +478,8 @@ line.
476478

477479
.. function:: getframeinfo(frame[, context])
478480

479-
Get information about a frame or traceback object. A 5-tuple is returned, the
480-
last five elements of the frame's frame record.
481+
Get information about a frame or traceback object. A :term:`named tuple`
482+
``Traceback(filename, lineno, function, code_context, index)`` is returned.
481483

482484

483485
.. function:: getouterframes(frame[, context])

Doc/library/re.rst

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,9 @@ The special characters are:
9898
string, and in :const:`MULTILINE` mode also matches before a newline. ``foo``
9999
matches both 'foo' and 'foobar', while the regular expression ``foo$`` matches
100100
only 'foo'. More interestingly, searching for ``foo.$`` in ``'foo1\nfoo2\n'``
101-
matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode.
101+
matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode; searching for
102+
a single ``$`` in ``'foo\n'`` will find two (empty) matches: one just before
103+
the newline, and one at the end of the string.
102104

103105
``'*'``
104106
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as

Lib/collections.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,23 +117,28 @@ def _replace(self, **kwds):
117117

118118
# test and demonstrate ability to override methods
119119
class Point(namedtuple('Point', 'x y')):
120+
__slots__ = ()
120121
@property
121122
def hypot(self):
122123
return (self.x ** 2 + self.y ** 2) ** 0.5
123124
def __str__(self):
124-
return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
125+
return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
125126

126-
for p in Point(3,4), Point(14,5), Point(9./7,6):
127+
for p in Point(3, 4), Point(14, 5/7.):
127128
print (p)
128129

129130
class Point(namedtuple('Point', 'x y')):
130131
'Point class with optimized _make() and _replace() without error-checking'
132+
__slots__ = ()
131133
_make = classmethod(tuple.__new__)
132134
def _replace(self, _map=map, **kwds):
133135
return self._make(_map(kwds.get, ('x', 'y'), self))
134136

135137
print(Point(11, 22)._replace(x=100))
136138

139+
Point3D = namedtuple('Point3D', Point._fields + ('z',))
140+
print(Point3D.__doc__)
141+
137142
import doctest
138143
TestResults = namedtuple('TestResults', 'failed attempted')
139144
print(TestResults(*doctest.testmod()))

Lib/decimal.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,12 @@
137137
import numbers as _numbers
138138
import copy as _copy
139139

140+
try:
141+
from collections import namedtuple as _namedtuple
142+
DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143+
except ImportError:
144+
DecimalTuple = lambda *args: args
145+
140146
# Rounding
141147
ROUND_DOWN = 'ROUND_DOWN'
142148
ROUND_HALF_UP = 'ROUND_HALF_UP'
@@ -841,7 +847,7 @@ def as_tuple(self):
841847
842848
To show the internals exactly as they are.
843849
"""
844-
return (self._sign, tuple(map(int, self._int)), self._exp)
850+
return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
845851

846852
def __repr__(self):
847853
"""Represents the number as an instance of Decimal."""

Lib/difflib.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,12 @@
3030

3131
__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
3232
'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
33-
'unified_diff', 'HtmlDiff']
33+
'unified_diff', 'HtmlDiff', 'Match']
3434

3535
import heapq
36+
from collections import namedtuple as _namedtuple
37+
38+
Match = _namedtuple('Match', 'a b size')
3639

3740
def _calculate_ratio(matches, length):
3841
if length:
@@ -363,7 +366,7 @@ def find_longest_match(self, alo, ahi, blo, bhi):
363366
364367
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
365368
>>> s.find_longest_match(0, 5, 0, 9)
366-
(0, 4, 5)
369+
Match(a=0, b=4, size=5)
367370
368371
If isjunk is defined, first the longest matching block is
369372
determined as above, but with the additional restriction that no
@@ -379,13 +382,13 @@ def find_longest_match(self, alo, ahi, blo, bhi):
379382
380383
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
381384
>>> s.find_longest_match(0, 5, 0, 9)
382-
(1, 0, 4)
385+
Match(a=1, b=0, size=4)
383386
384387
If no blocks match, return (alo, blo, 0).
385388
386389
>>> s = SequenceMatcher(None, "ab", "c")
387390
>>> s.find_longest_match(0, 2, 0, 1)
388-
(0, 0, 0)
391+
Match(a=0, b=0, size=0)
389392
"""
390393

391394
# CAUTION: stripping common prefix or suffix would be incorrect.
@@ -452,7 +455,7 @@ def find_longest_match(self, alo, ahi, blo, bhi):
452455
a[besti+bestsize] == b[bestj+bestsize]:
453456
bestsize = bestsize + 1
454457

455-
return besti, bestj, bestsize
458+
return Match(besti, bestj, bestsize)
456459

457460
def get_matching_blocks(self):
458461
"""Return list of triples describing matching subsequences.
@@ -469,8 +472,8 @@ def get_matching_blocks(self):
469472
triple with n==0.
470473
471474
>>> s = SequenceMatcher(None, "abxcd", "abcd")
472-
>>> s.get_matching_blocks()
473-
[(0, 0, 2), (3, 2, 2), (5, 4, 0)]
475+
>>> list(s.get_matching_blocks())
476+
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
474477
"""
475478

476479
if self.matching_blocks is not None:
@@ -523,7 +526,7 @@ def get_matching_blocks(self):
523526

524527
non_adjacent.append( (la, lb, 0) )
525528
self.matching_blocks = non_adjacent
526-
return self.matching_blocks
529+
return map(Match._make, self.matching_blocks)
527530

528531
def get_opcodes(self):
529532
"""Return list of 5-tuples describing how to turn a into b.

0 commit comments

Comments
 (0)