Raymond Hettinger | 80ed4d4 | 2012-06-09 18:46:45 -0700 | [diff] [blame] | 1 | ################################################################################ |
| 2 | ### Simple tests |
| 3 | ################################################################################ |
| 4 | |
| 5 | # verify that instances can be pickled |
| 6 | from collections import namedtuple |
| 7 | from pickle import loads, dumps |
| 8 | Point = namedtuple('Point', 'x, y', True) |
| 9 | p = Point(x=10, y=20) |
| 10 | assert p == loads(dumps(p)) |
| 11 | |
| 12 | # test and demonstrate ability to override methods |
| 13 | class Point(namedtuple('Point', 'x y')): |
| 14 | __slots__ = () |
| 15 | @property |
| 16 | def hypot(self): |
| 17 | return (self.x ** 2 + self.y ** 2) ** 0.5 |
| 18 | def __str__(self): |
| 19 | return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) |
| 20 | |
| 21 | for p in Point(3, 4), Point(14, 5/7.): |
| 22 | print (p) |
| 23 | |
| 24 | class Point(namedtuple('Point', 'x y')): |
| 25 | 'Point class with optimized _make() and _replace() without error-checking' |
| 26 | __slots__ = () |
| 27 | _make = classmethod(tuple.__new__) |
| 28 | def _replace(self, _map=map, **kwds): |
| 29 | return self._make(_map(kwds.get, ('x', 'y'), self)) |
| 30 | |
| 31 | print(Point(11, 22)._replace(x=100)) |
| 32 | |
| 33 | Point3D = namedtuple('Point3D', Point._fields + ('z',)) |
| 34 | print(Point3D.__doc__) |
| 35 | |
| 36 | import doctest, collections |
| 37 | TestResults = namedtuple('TestResults', 'failed attempted') |
| 38 | print(TestResults(*doctest.testmod(collections))) |