8000 bpo-37836: support .as_integer_ratio() in Fraction by jdemeyer · Pull Request #15327 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

bpo-37836: support .as_integer_ratio() in Fraction #15327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
bpo-37836: optimize creating Fraction from integers
  • Loading branch information
jdemeyer committed Aug 19, 2019
commit f1b1e8cf06c9e1cd6607e8ec94fd3c758f648928
12 changes: 8 additions & 4 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,6 @@ def _as_integer_ratio(obj):
method or is an instance of ``numbers.Rational``. Return ``NotImplemented``
if neither works.
"""
# Fast path
if type(obj) is int:
return (obj, 1)

try:
f = obj.as_integer_ratio
except AttributeError:
Expand Down Expand Up @@ -139,6 +135,11 @@ def __new__(cls, numerator=0, denominator=None, *, _normalize=True):
self = super(Fraction, cls).__new__(cls)

if denominator is None:
# Fast path for Fraction(int)
if type(numerator) is int:
self._numerator = numerator
self._denominator = 1
return self
nd = _as_integer_ratio(numerator)
if nd is not NotImplemented:
numerator, denominator = nd
Expand Down Expand Up @@ -177,6 +178,9 @@ def __new__(cls, numerator=0, denominator=None, *, _normalize=True):
"a Rational instance or have "
"an as_integer_ratio() method")

elif type(numerator) is int is type(denominator):
# Fast path for Fraction(int, int)
pass
else:
x = _as_integer_ratio(numerator)
y = _as_integer_ratio(denominator)
Expand Down
0