[Python-checkins] r59810 - in python/trunk: Doc/library/collections.rst Lib/collections.py

raymond.hettinger python-checkins at python.org
Mon Jan 7 10:03:49 CET 2008


Author: raymond.hettinger
Date: Mon Jan 7 10:03:49 2008
New Revision: 59810
Modified:
 python/trunk/Doc/library/collections.rst
 python/trunk/Lib/collections.py
Log:
Add another named tuple subclassing example.
Modified: python/trunk/Doc/library/collections.rst
==============================================================================
--- python/trunk/Doc/library/collections.rst	(original)
+++ python/trunk/Doc/library/collections.rst	Mon Jan 7 10:03:49 2008
@@ -527,6 +527,14 @@
 Point(x=2.000, y=5.000, hypot=5.385) 
 Point(x=1.286, y=6.000, hypot=6.136)
 
+Another use for subclassing is to replace performance critcal methods with
+faster versions that bypass error-checking and localize variable access:
+
+ >>> class Point(namedtuple('Point', 'x y')):
+ _make = classmethod(tuple.__new__)
+ def _replace(self, _map=map, **kwds):
+ return self._make(_map(kwds.pop, ('x', 'y'), self))
+
 Default values can be implemented by starting with a prototype instance
 and customizing it with :meth:`_replace`:
 
Modified: python/trunk/Lib/collections.py
==============================================================================
--- python/trunk/Lib/collections.py	(original)
+++ python/trunk/Lib/collections.py	Mon Jan 7 10:03:49 2008
@@ -125,6 +125,14 @@
 
 print Point(3, 4),'\n', Point(2, 5), '\n', Point(9./7, 6)
 
+ class Point(namedtuple('Point', 'x y')):
+ 'Point class with optimized _make() and _replace() without error-checking'
+ _make = classmethod(tuple.__new__)
+ def _replace(self, _map=map, **kwds):
+ return self._make(_map(kwds.pop, ('x', 'y'), self))
+
+ print Point(11, 22)._replace(x=100)
+
 import doctest
 TestResults = namedtuple('TestResults', 'failed attempted')
 print TestResults(*doctest.testmod())


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /