blob: 763e38e0c40c0dea67a0b82c6b7646171cbaac12 [file] [log] [blame]
Raymond Hettinger80ed4d42012-06-09 18:46:45 -07001################################################################################
2### Simple tests
3################################################################################
4
5# verify that instances can be pickled
6from collections import namedtuple
7from pickle import loads, dumps
8Point = namedtuple('Point', 'x, y', True)
9p = Point(x=10, y=20)
10assert p == loads(dumps(p))
11
12# test and demonstrate ability to override methods
13class 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
21for p in Point(3, 4), Point(14, 5/7.):
22 print (p)
23
24class 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
31print(Point(11, 22)._replace(x=100))
32
33Point3D = namedtuple('Point3D', Point._fields + ('z',))
34print(Point3D.__doc__)
35
36import doctest, collections
37TestResults = namedtuple('TestResults', 'failed attempted')
38print(TestResults(*doctest.testmod(collections)))