[Python-checkins] bpo-44154: optimize Fraction pickling (GH-26186)

rhettinger webhook-mailer at python.org
Mon May 17 03:20:18 EDT 2021


https://github.com/python/cpython/commit/b102dd598dd2666b72e93ae53ae813d1e88f186c
commit: b102dd598dd2666b72e93ae53ae813d1e88f186c
branch: main
author: Sergey B Kirpichev <2155800+skirpichev at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2021-05-17T00:20:02-07:00
summary:

bpo-44154: optimize Fraction pickling (GH-26186)

files:
A Misc/NEWS.d/next/Library/2021-05-17-07-24-24.bpo-44154.GRI5bf.rst
M Lib/fractions.py
M Lib/test/test_fractions.py

diff --git a/Lib/fractions.py b/Lib/fractions.py
index 96047beb4546a..64a8959d7d48e 100644
--- a/Lib/fractions.py
+++ b/Lib/fractions.py
@@ -735,7 +735,7 @@ def __bool__(a):
     # support for pickling, copy, and deepcopy
 
     def __reduce__(self):
-        return (self.__class__, (str(self),))
+        return (self.__class__, (self._numerator, self._denominator))
 
     def __copy__(self):
         if type(self) == Fraction:
diff --git a/Lib/test/test_fractions.py b/Lib/test/test_fractions.py
index b92552531d6bb..949ddd9072862 100644
--- a/Lib/test/test_fractions.py
+++ b/Lib/test/test_fractions.py
@@ -10,6 +10,7 @@
 import sys
 import unittest
 from copy import copy, deepcopy
+import pickle
 from pickle import dumps, loads
 F = fractions.Fraction
 
@@ -691,7 +692,8 @@ def testApproximateCos1(self):
     def test_copy_deepcopy_pickle(self):
         r = F(13, 7)
         dr = DummyFraction(13, 7)
-        self.assertEqual(r, loads(dumps(r)))
+        for proto in range(0, pickle.HIGHEST_PROTOCOL + 1):
+            self.assertEqual(r, loads(dumps(r, proto)))
         self.assertEqual(id(r), id(copy(r)))
         self.assertEqual(id(r), id(deepcopy(r)))
         self.assertNotEqual(id(dr), id(copy(dr)))
diff --git a/Misc/NEWS.d/next/Library/2021-05-17-07-24-24.bpo-44154.GRI5bf.rst b/Misc/NEWS.d/next/Library/2021-05-17-07-24-24.bpo-44154.GRI5bf.rst
new file mode 100644
index 0000000000000..3ec326e875ecc
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-05-17-07-24-24.bpo-44154.GRI5bf.rst
@@ -0,0 +1 @@
+Optimize :class:`fractions.Fraction` pickling for large components.



More information about the Python-checkins mailing list