[issue1682] Move Demo/classes/Rat.py to Lib/fractions.py and fix it up.

Guido van Rossum report at bugs.python.org
Thu Feb 14 18:08:55 CET 2008


Guido van Rossum added the comment:

PS. I can shave off nearly 4 usec of the constructor like this:

-        self = super(Fraction, cls).__new__(cls)
+        if cls is Fraction:
+            self = object.__new__(cls)
+        else:
+            self = super().__new__(cls)

This would seem to give an upper bound for the gain you can make by
moving the check for instantiating an abstract class to C.  Your call.  

I also found that F(2,3)+F(5,7) takes about 22 usecs (or 18 using the
above hack).

Inlining the common case for addition (Fraction+Fraction) made that go
down to 14 usec (combined with the above hack):

-    __add__, __radd__ = _operator_fallbacks(_add, operator.add)
+    __xadd__, __radd__ = _operator_fallbacks(_add, operator.add)
 
+    def __add__(self, other):
+        if type(other) is Fraction:
+            na = self._numerator
+            da = self._denominator
+            nb = other._numerator
+            db = other._denominator
+            return Fraction(na*db + nb*da, da*db)
+        return self.__xadd__(other)
+

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue1682>
__________________________________


More information about the Python-bugs-list mailing list