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