From: Raymond Hettinger Date: Fri, 25 Jan 2008 00:21:54 +0000 (+0000) Subject: Add support for copy, deepcopy, and pickle. X-Git-Tag: v2.6a1~418 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=a6216749fb88fb508cd469839d77d4264a881bd4;p=python Add support for copy, deepcopy, and pickle. --- diff --git a/Lib/rational.py b/Lib/rational.py index 0d3ea2f04f..031ee0f20e 100755 --- a/Lib/rational.py +++ b/Lib/rational.py @@ -490,3 +490,18 @@ class Rational(RationalAbc): 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) diff --git a/Lib/test/test_rational.py b/Lib/test/test_rational.py index 3242e43886..20abce26df 100644 --- a/Lib/test/test_rational.py +++ b/Lib/test/test_rational.py @@ -6,6 +6,8 @@ import math 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 @@ class RationalTest(unittest.TestCase): 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)