Repository navigation
Open
Labels
performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Description
| BPO | 28716 |
|---|---|
| Nosy | @rhettinger, @mdickinson, @scoder, @stevendaprano, @serhiy-storchaka, @jdemeyer, @eric-wieser, @wm75, @MojoVampire |
| Files |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee = None
closed_at = None
created_at = <Date 2016-11-16.18:06:27.650>
labels = ['3.8', 'type-bug', 'library']
title = 'Fractions instantiation revisited'
updated_at = <Date 2019-08-05.09:04:19.247>
user = 'https://github.com/wm75'bugs.python.org fields:
activity = <Date 2019-08-05.09:04:19.247>
actor = 'jdemeyer'
assignee = 'none'
closed = False
closed_date = None
closer = None
components = ['Library (Lib)']
creation = <Date 2016-11-16.18:06:27.650>
creator = 'wolma'
dependencies = []
files = ['45507']
hgrepos = []
issue_num = 28716
keywords = ['patch']
message_count = 13.0
messages = ['280977', '280981', '280995', '280997', '280998', '280999', '305611', '310470', '313208', '313741', '313753', '313786', '349037']
nosy_count = 9.0
nosy_names = ['rhettinger', 'mark.dickinson', 'scoder', 'steven.daprano', 'serhiy.storchaka', 'jdemeyer', 'Eric.Wieser', 'wolma', 'josh.r']
pr_nums = []
priority = 'normal'
resolution = None
stage = None
status = 'open'
superseder = None
type = 'behavior'
url = 'https://bugs.python.org/issue28716'
versions = ['Python 3.8']Linked PRs
Metadata
Metadata
Assignees
Labels
performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Activity
eric-wieser commentedon Mar 13, 2018
Yes, exactly. Conversely, there's little gain in implementing it until
Fractionsupports calling it.rhettinger commentedon Mar 13, 2018
FYI, adding int.as_integer_ratio() is being taken care in a separate issue: https://bugs.python.org/issue33073 . I've set it aside for a beginning core-dev mentee to work on because it is simple and self-contained. Pretty much all the related work can be done here.
jdemeyer commentedon Aug 5, 2019
See https://discuss.python.org/t/pep-3141-ratio-instead-of-numerator-denominator/2037/24?u=jdemeyer for a proposal to define a new dunder __ratio__ (instead of as_integer_ratio) for this.
pythongh-72902: speedup Fraction.from_Decimal/float in typical cases
skirpichev commentedon May 1, 2025
@wm75, here is a pr to speedup
from_*()methods: #133251.Let me know if you wish to continue your work on the Fraction constructor. Or I can prepare a patch and mention you as co-author.
IIUIC, at this point relevant parts of your proposal are: 1) move "str" case up (over numbers.Rational), 2) reimplement string parsing without regexps.
Below my simple benchmarks. The patch1 just do 1), the patch2 (included below) - solves also 2).
Details
pythongh-72902: improve Fraction(str) speed (don't use regexp's)
skirpichev commentedon May 14, 2025
Second pr is available to review: #133994
pythongh-72902: improve Fraction(str) speed (don't use regexp's)
serhiy-storchaka commentedon May 19, 2025
First, benchmark how it would affect
Fraction->Fractionconversion. While it looks meanless,Fractions()can be applied to a collection of numbers -- integers, floating point, rational... We can also move down theas_integer_ratiocheck, but we need to benchmark Deciaml -> Fraction conversion. Thefloatcheck can be left, and it can be simplified totype(numerator) is floatif there is a benefit. Just for the case, benchmark conversion fromintandfloatsubclasses -- I do not think this is an important use case, but we should know how large the impact.skirpichev commentedon May 20, 2025
@serhiy-storchaka, here are more extended tests on top of #133994 (at e383bdb):
Details
move-abc patch:
serhiy-storchaka commentedon May 20, 2025
Well, it looks that the only slowed down case is for rational numbers without
as_integer_ratio(). I think that from a practical point of view it is worth it.pythongh-72902: improve Fraction constructor speed for typical inputs
skirpichev commentedon May 20, 2025
Ok, I split out this change to #134320
gh-72902: improve Fraction constructor speed for typical inputs (GH-1…
pythongh-72902: improve Fraction constructor speed for typical inputs (…
pythongh-72902: improve Fraction constructor speed for typical inputs (…
gh-72902: Speedup Fraction.from_decimal/float in typical cases (GH-13…
scoder commentedon Jun 26, 2026
The instantiation fast paths make the general assumption that the
.as_integer_ratio()method returns its ratio in lowest terms. This is certainly true for the builtin types, but subtypes and other types (e.g. arbitrary otherRationaltypes) might not follow this constraint. The.as_integer_ratio()method is only 'formally' documented for the builtin types that provide it, not as a general protocol. Thenumbersmodule of ABCs does not mention the method.Therefore, I wonder if we should generally assume that all types obey this constraint, including builtin subtypes and user provided types, or whether we should restrict optimisations to the exact builtin types and otherwise assume (potentially) non-normalised return values, bailing to the regular GCD-normalisation paths.
For performance reasons, assuming a builtin-like implementation that returns lowest terms ratios is obviously attractive, but optimisations should only be applied within safe assumptions, not forfeit correctness. And I would generally expect the large majority of cases (those that merit optimisation) to actually pass the exact builtin types and nothing else, so we shouldn't lose much by playing it safe.
Opinions?
skirpichev commentedon Jun 27, 2026
And this is correct in the merged pr #133251, as it affects only float/Decimal subclasses. Someone can override contract from the parent class method to return None and blow up a nuke instead. I see no way to play nicely with such morons.
That's true, just invalid for builtin subtypes. It was my concern as well:
#120271 (comment)
Notably, that numpy types doesn't document such constraint (despite it seems to be valid):
>>> help(np.float128.as_integer_ratio) Help on method descriptor as_integer_ratio: as_integer_ratio(self, /) unbound numpy.longdouble method longdouble.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original floating point number, and with a positive denominator. Raise `OverflowError` on infinities and a `ValueError` on NaNs. >>> np.longdouble(10.0).as_integer_ratio() (10, 1) >>> np.longdouble(0.0).as_integer_ratio() (0, 1) >>> np.longdouble(-.25).as_integer_ratio() (-1, 4)(Some canonicalization was mentioned, however.)
This affects following cases:
cpython/Lib/fractions.py
Lines 245 to 250 in 1812162
and:
cpython/Lib/fractions.py
Lines 326 to 329 in 1812162
This assumption was introduced in c8d2630. CC @serhiy-storchaka.
My opinion is that this is API similar to numerator/denominator pairs, it's for interoperation with the Rational type and should be mentioned in the numbers ABC as an optional method for Real types and mandatory for Rational's. It should return a canonicalized fraction.
BTW, there could be a more generic API,
limit_denominator()-like. With infinitemax_denominator- this should provide same value asas_integer_ratio()for Rational types and for some Real types (e.g. floating-point numbers). Though, in certain cases (e.g. for interval arithmetic) - infinitemax_denominatordoesn't make any sense.gh-72902: improve `Fraction(str)` speed (#149024)