Minor fix-ups to named tuples:
* Make the _replace() method respect subclassing.
* Using property() to make _fields read-only wasn't a good idea.
It caused len(Point._fields) to fail.
* Add note to _cast() about length checking and alternative with the star-operator.
diff --git a/Lib/collections.py b/Lib/collections.py
index c6d0d0f..487b119 100644
--- a/Lib/collections.py
+++ b/Lib/collections.py
@@ -60,6 +60,7 @@
template = '''class %(typename)s(tuple):
'%(typename)s(%(argtxt)s)' \n
__slots__ = () \n
+ _fields = %(field_names)r \n
def __new__(cls, %(argtxt)s):
return tuple.__new__(cls, (%(argtxt)s)) \n
_cast = classmethod(tuple.__new__) \n
@@ -70,10 +71,7 @@
return {%(dicttxt)s} \n
def _replace(self, **kwds):
'Return a new %(typename)s object replacing specified fields with new values'
- return %(typename)s._cast(map(kwds.get, %(field_names)r, self)) \n
- @property
- def _fields(self):
- return %(field_names)r \n\n''' % locals()
+ return self.__class__._cast(map(kwds.get, %(field_names)r, self)) \n\n''' % locals()
for i, name in enumerate(field_names):
template += ' %s = property(itemgetter(%d))\n' % (name, i)
if verbose:
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index edffbbe..5e71399 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -17,6 +17,7 @@
self.assertEqual(Point.__slots__, ())
self.assertEqual(Point.__module__, __name__)
self.assertEqual(Point.__getitem__, tuple.__getitem__)
+ self.assertEqual(Point._fields, ('x', 'y'))
self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi') # type has non-alpha char
self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi') # type has keyword
@@ -51,14 +52,6 @@
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
self.assertEqual(p._asdict(), dict(x=11, y=22)) # test _asdict method
- # Verify that _fields is read-only
- try:
- p._fields = ('F1' ,'F2')
- except AttributeError:
- pass
- else:
- self.fail('The _fields attribute needs to be read-only')
-
# verify that field string can have commas
Point = namedtuple('Point', 'x, y')
p = Point(x=11, y=22)