]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Issue #9507: Named tuple repr will now automatically display the right
authorRaymond Hettinger <python@rcn.com>
Sun, 8 Aug 2010 01:13:42 +0000 (01:13 +0000)
committerRaymond Hettinger <python@rcn.com>
Sun, 8 Aug 2010 01:13:42 +0000 (01:13 +0000)
name in a tuple subclass.

Doc/library/collections.rst
Lib/collections.py
Lib/test/test_collections.py
Misc/NEWS

index 741c7a04a94739c9a3a11208ab8510e510a27d36..66d373d2c086bb79583ed20d3945aac29351bb92 100644 (file)
@@ -605,7 +605,7 @@ Example:
    <BLANKLINE>
            def __repr__(self):
                'Return a nicely formatted representation string'
-               return 'Point(x=%r, y=%r)' % self
+               return self.__class__.__name__ + '(x=%r, y=%r)' % self
    <BLANKLINE>
            def _asdict(self):
                'Return a new OrderedDict which maps field names to their values'
index 2ce46de4883c2911fca0603f32aff8b9e72677da..1a43afbe894fbf850f6b9c25c1e42ad09835101c 100644 (file)
@@ -240,7 +240,7 @@ def namedtuple(typename, field_names, verbose=False, rename=False):
             return result \n
         def __repr__(self):
             'Return a nicely formatted representation string'
-            return '%(typename)s(%(reprtxt)s)' %% self \n
+            return self.__class__.__name__ + '(%(reprtxt)s)' %% self \n
         def _asdict(self):
             'Return a new OrderedDict which maps field names to their values'
             return OrderedDict(zip(self._fields, self)) \n
index 69c4a9f173efe6f72fd2f01a1b7bc3f850ee02d2..2af94bff4c4f78d6c2984af3f325a22413a9bab2 100644 (file)
@@ -218,6 +218,16 @@ class TestNamedTuple(unittest.TestCase):
         # test __getnewargs__
         self.assertEqual(t.__getnewargs__(), values)
 
+    def test_repr(self):
+        with support.captured_stdout() as template:
+            A = namedtuple('A', 'x', verbose=True)
+        self.assertEqual(repr(A(1)), 'A(x=1)')
+        # repr should show the name of the subclass
+        class B(A):
+            pass
+        self.assertEqual(repr(B(1)), 'B(x=1)')
+
+
 class ABCTestCase(unittest.TestCase):
 
     def validate_abstract_methods(self, abc, *names):
index 4f99d70674c3026f39fda93555482c8303de9f23..c0e3fc7ce6df57740395befa2025a5f234654f99 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -24,6 +24,9 @@ Core and Builtins
 Extensions
 ----------
 
+- Issue #9507:  Named tuple repr will now automatically display the right
+  name in a tuple subclass.
+
 - Issue #9324: Add parameter validation to signal.signal on Windows in order
   to prevent crashes.