[Python-checkins] r60270 - in python/trunk/Lib: rational.py test/test_rational.py

raymond.hettinger python-checkins at python.org
Fri Jan 25 01:21:54 CET 2008


Author: raymond.hettinger
Date: Fri Jan 25 01:21:54 2008
New Revision: 60270
Modified:
 python/trunk/Lib/rational.py
 python/trunk/Lib/test/test_rational.py
Log:
Add support for copy, deepcopy, and pickle.
Modified: python/trunk/Lib/rational.py
==============================================================================
--- python/trunk/Lib/rational.py	(original)
+++ python/trunk/Lib/rational.py	Fri Jan 25 01:21:54 2008
@@ -490,3 +490,18 @@
 def __nonzero__(a):
 """a != 0"""
 return a.numerator != 0
+
+ # support for pickling, copy, and deepcopy
+
+ def __reduce__(self):
+ return (self.__class__, (str(self),))
+
+ def __copy__(self):
+ if type(self) == Rational:
+ return self # I'm immutable; therefore I am my own clone
+ return self.__class__(self.numerator, self.denominator)
+
+ def __deepcopy__(self, memo):
+ if type(self) == Rational:
+ return self # My components are also immutable
+ return self.__class__(self.numerator, self.denominator)
Modified: python/trunk/Lib/test/test_rational.py
==============================================================================
--- python/trunk/Lib/test/test_rational.py	(original)
+++ python/trunk/Lib/test/test_rational.py	Fri Jan 25 01:21:54 2008
@@ -6,6 +6,8 @@
 import operator
 import rational
 import unittest
+from copy import copy, deepcopy
+from cPickle import dumps, loads
 R = rational.Rational
 
 def _components(r):
@@ -359,6 +361,12 @@
 s += num / fact * sign
 self.assertAlmostEquals(math.cos(1), s)
 
+ def test_copy_deepcopy_pickle(self):
+ r = R(13, 7)
+ self.assertEqual(r, loads(dumps(r)))
+ self.assertEqual(id(r), id(copy(r)))
+ self.assertEqual(id(r), id(deepcopy(r)))
+
 def test_main():
 run_unittest(RationalTest)
 


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /