__main__.py 1.2 KB

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