Skip to content

Fractions instantiation revisited #72902

Open

Description

@wm75
mannequin
BPO 28716
Nosy @rhettinger, @mdickinson, @scoder, @stevendaprano, @serhiy-storchaka, @jdemeyer, @eric-wieser, @wm75, @MojoVampire
Files
  • fractions.patch
  • 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

    Activity

    1. eric-wieser commented on Mar 13, 2018

      eric-wiesermannequin
      Mannequin

      Are you suggesting that if they were to implement as_integer_ratio at some point in the future, then they'd become compatible with Fraction

      Yes, exactly. Conversely, there's little gain in implementing it until Fraction supports calling it.

    2. rhettinger commented on Mar 13, 2018

      @rhettinger
      Contributor

      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.

    3. jdemeyer commented on Aug 5, 2019

      @jdemeyer
      Contributor

      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.

    4. transferred this issue fromon Apr 10, 2022
    5. added a commit that references this issue on May 1, 2025
    6. self-assigned this
      on May 1, 2025
    7. added
      type-feature
      performance
      and removed
      type-bug
      3.8 (EOL)
      on May 1, 2025
    8. skirpichev commented on May 1, 2025

      @skirpichev
      Member

      @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).

      Benchmark ref patch1 patch2
      Fraction(myint) 5.29 us 6.71 us: 1.27x slower 6.67 us: 1.26x slower
      Fraction('123') 17.8 us 14.9 us: 1.19x faster 9.31 us: 1.91x faster
      Fraction('1/3') 18.3 us 15.3 us: 1.20x faster 9.17 us: 1.99x faster
      Fraction('1.2e-3') 24.8 us 21.9 us: 1.13x faster 14.3 us: 1.73x faster
      Fraction('-.2') 22.2 us 19.3 us: 1.15x faster 13.5 us: 1.65x faster
      Geometric mean (ref) 1.08x faster 1.54x faster
      Details
      # bench.py
      import pyperf
      from fractions import Fraction as F
      from numbers import Integral
      
      runner = pyperf.Runner()
      s = 'Fraction'
      class myint:
          numerator = 123
          denominator = 1
          def __int__(self):
              return 123
          def __repr__(self):
              return "myint"
      Integral.register(myint)
      for v in [myint(), "123", "1/3", "1.2e-3", "-.2"]:
          r = s + '(' + repr(v) + ')'
          runner.bench_func(r, F, v)
      diff --git a/Lib/fractions.py b/Lib/fractions.py
      index fa722589fb..55d1113b4a 100644
      --- a/Lib/fractions.py
      +++ b/Lib/fractions.py
      @@ -53,20 +53,6 @@ def _hash_algorithm(numerator, denominator):
           result = hash_ if numerator >= 0 else -hash_
           return -2 if result == -1 else result
       
      -_RATIONAL_FORMAT = re.compile(r"""
      -    \A\s*                                  # optional whitespace at the start,
      -    (?P<sign>[-+]?)                        # an optional sign, then
      -    (?=\d|\.\d)                            # lookahead for digit or .digit
      -    (?P<num>\d*|\d+(_\d+)*)                # numerator (possibly empty)
      -    (?:                                    # followed by
      -       (?:\s*/\s*(?P<denom>\d+(_\d+)*))?   # an optional denominator
      -    |                                      # or
      -       (?:\.(?P<decimal>\d*|\d+(_\d+)*))?  # an optional fractional part
      -       (?:E(?P<exp>[-+]?\d+(_\d+)*))?      # and optional exponent
      -    )
      -    \s*\Z                                  # and optional whitespace to finish
      -""", re.VERBOSE | re.IGNORECASE)
      -
       
       # Helpers for formatting
       
      @@ -238,11 +224,6 @@ def __new__(cls, numerator=0, denominator=None):
                       self._denominator = 1
                       return self
       
      -            elif isinstance(numerator, numbers.Rational):
      -                self._numerator = numerator.numerator
      -                self._denominator = numerator.denominator
      -                return self
      -
                   elif (isinstance(numerator, float) or
                         (not isinstance(numerator, type) and
                          hasattr(numerator, 'as_integer_ratio'))):
      @@ -252,31 +233,56 @@ def __new__(cls, numerator=0, denominator=None):
       
                   elif isinstance(numerator, str):
                       # Handle construction from strings.
      -                m = _RATIONAL_FORMAT.match(numerator)
      -                if m is None:
      +                fraction_literal = numerator
      +                num, _, denom = fraction_literal.partition('/')
      +                try:
      +                    num = num.strip()
      +                    denom = denom.strip()
      +                    if _ == '':
      +                        # Numerator-only form allows for optional fractional
      +                        # and exponent parts.
      +                        # Partition the fraction literal on the exponent sign,
      +                        # while ignoring leading and trailing whitespace
      +                        # and the case of the exponent sign.
      +                        num, _, exp = num.replace('e', 'E').partition('E')
      +                        if _ and not exp:
      +                            # No exponent notation without value!
      +                            raise ValueError
      +                        num, _, decimal = num.partition('.')
      +                        shift = 0
      +                        if decimal:
      +                            # Zero-pad integer-less fraction literals.
      +                            if num == '' or num == '+':
      +                                num = '0'
      +                            elif num == '-':
      +                                num += '0'
      +                            # Joining literal parts by underscores ensures
      +                            # that result strings can only be parsed as ints
      +                            # if there parts were parseable.
      +                            num = f'{num}_{decimal}'
      +                            shift -= len(decimal)-decimal.count('_')
      +                        if exp:
      +                            shift += int(exp)
      +                        numerator = int(num)
      +                        denominator = 1
      +                        if shift > 0:
      +                            numerator *= 10 ** shift
      +                        elif shift < 0:
      +                            denominator = 10 ** -shift
      +
      +                    elif num and denom and num[-1].isdigit() and denom[0].isdigit():
      +                        numerator = int(num)
      +                        denominator = int(denom)
      +                    else:
      +                        raise ValueError
      +                except ValueError:
                           raise ValueError('Invalid literal for Fraction: %r' %
      -                                     numerator)
      -                numerator = int(m.group('num') or '0')
      -                denom = m.group('denom')
      -                if denom:
      -                    denominator = int(denom)
      -                else:
      -                    denominator = 1
      -                    decimal = m.group('decimal')
      -                    if decimal:
      -                        decimal = decimal.replace('_', '')
      -                        scale = 10**len(decimal)
      -                        numerator = numerator * scale + int(decimal)
      -                        denominator *= scale
      -                    exp = m.group('exp')
      -                    if exp:
      -                        exp = int(exp)
      -                        if exp >= 0:
      -                            numerator *= 10**exp
      -                        else:
      -                            denominator *= 10**-exp
      -                if m.group('sign') == '-':
      -                    numerator = -numerator
      +                                     fraction_literal)
      +
      +            elif isinstance(numerator, numbers.Rational):
      +                self._numerator = numerator.numerator
      +                self._denominator = numerator.denominator
      +                return self
       
                   else:
                       raise TypeError("argument should be a string or a Rational "
    9. added a commit that references this issue on May 14, 2025
    10. skirpichev commented on May 14, 2025

      @skirpichev
      Member

      Second pr is available to review: #133994

    11. removed their assignment
      on May 14, 2025
    12. added a commit that references this issue on May 16, 2025
    13. serhiy-storchaka commented on May 19, 2025

      @serhiy-storchaka
      Member

      @serhiy-storchaka, but what about other change, i.e. moving down numbers.Rational check? Maybe I should factor out this to a separate pr? See benchmarks (third column) and my arguments for this.

      First, benchmark how it would affect Fraction -> Fraction conversion. While it looks meanless, Fractions() can be applied to a collection of numbers -- integers, floating point, rational... We can also move down the as_integer_ratio check, but we need to benchmark Deciaml -> Fraction conversion. The float check can be left, and it can be simplified to type(numerator) is float if there is a benefit. Just for the case, benchmark conversion from int and float subclasses -- I do not think this is an important use case, but we should know how large the impact.

    14. self-assigned this
      on May 20, 2025
    15. skirpichev commented on May 20, 2025

      @skirpichev
      Member

      @serhiy-storchaka, here are more extended tests on top of #133994 (at e383bdb):

      Benchmark ref patch move-abc
      Fraction(myint) 5.67 us 7.10 us: 1.25x slower 7.02 us: 1.24x slower
      Fraction(Fraction(1, 2)) 5.86 us 4.87 us: 1.20x faster 4.85 us: 1.21x faster
      Fraction(Decimal('0.25')) 11.1 us 8.05 us: 1.38x faster 8.01 us: 1.39x faster
      Fraction(IntSubclass(123)) 6.03 us 5.08 us: 1.19x faster 5.06 us: 1.19x faster
      Fraction(FloatSubclass(0.25)) 7.71 us 4.28 us: 1.80x faster 4.27 us: 1.81x faster
      Fraction('123') 19.3 us 12.2 us: 1.58x faster 15.9 us: 1.21x faster
      Fraction('1/3') 19.6 us 9.49 us: 2.07x faster 16.4 us: 1.20x faster
      Fraction('1.2e-3') 26.2 us 16.9 us: 1.55x faster 23.1 us: 1.13x faster
      Fraction('-.2') 23.4 us 15.1 us: 1.55x faster 20.3 us: 1.15x faster
      Geometric mean (ref) 1.41x faster 1.21x faster
      Details

      move-abc patch:

      diff --git a/Lib/fractions.py b/Lib/fractions.py
      index 8163e3bb59..063f28478c 100644
      --- a/Lib/fractions.py
      +++ b/Lib/fractions.py
      @@ -238,11 +238,6 @@ def __new__(cls, numerator=0, denominator=None):
                       self._denominator = 1
                       return self
       
      -            elif isinstance(numerator, numbers.Rational):
      -                self._numerator = numerator.numerator
      -                self._denominator = numerator.denominator
      -                return self
      -
                   elif (isinstance(numerator, float) or
                         (not isinstance(numerator, type) and
                          hasattr(numerator, 'as_integer_ratio'))):
      @@ -278,6 +273,11 @@ def __new__(cls, numerator=0, denominator=None):
                       if m.group('sign') == '-':
                           numerator = -numerator
       
      +            elif isinstance(numerator, numbers.Rational):
      +                self._numerator = numerator.numerator
      +                self._denominator = numerator.denominator
      +                return self
      +
                   else:
                       raise TypeError("argument should be a string or a Rational "
                                       "instance or have the as_integer_ratio() method")
      # bench.py
      import pyperf
      from fractions import Fraction as F
      from decimal import Decimal as D
      from numbers import Integral
      
      runner = pyperf.Runner()
      s = 'Fraction'
      class MyInt:
          numerator = 123
          denominator = 1
          def __int__(self):
              return 123
          def __repr__(self):
              return "myint"
      class IntSubclass(int):
          def __repr__(self):
              return 'IntSubclass('+super().__repr__()+')'
      class FloatSubclass(float):
          def __repr__(self):
              return 'FloatSubclass('+super().__repr__()+')'
      
      Integral.register(MyInt)
      for v in [MyInt(), F(1, 2), D("0.25"),
                IntSubclass(123), FloatSubclass(0.25),
                "123", "1/3", "1.2e-3", "-.2"]:
          r = s + '(' + repr(v) + ')'
          runner.bench_func(r, F, v)
    16. serhiy-storchaka commented on May 20, 2025

      @serhiy-storchaka
      Member

      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.

    17. added a commit that references this issue on May 20, 2025
    18. skirpichev commented on May 20, 2025

      @skirpichev
      Member

      Ok, I split out this change to #134320

    19. removed their assignment
      on May 20, 2025
    20. added a commit that references this issue on May 20, 2025
    21. added a commit that references this issue on Jul 12, 2025
    22. added a commit that references this issue on Aug 4, 2025
    23. added a commit that references this issue on May 25, 2026
    24. scoder commented on Jun 26, 2026

      @scoder
      Contributor

      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 other Rational types) 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. The numbers module 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?

    25. skirpichev commented on Jun 27, 2026

      @skirpichev
      Member

      The instantiation fast paths make the general assumption that the .as_integer_ratio() method returns its ratio in lowest terms.

      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.

      other types (e.g. arbitrary other Rational types) might not follow this constraint.

      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

      elif (isinstance(numerator, float) or
      (not isinstance(numerator, type) and
      hasattr(numerator, 'as_integer_ratio'))):
      # Exact conversion
      self._numerator, self._denominator = numerator.as_integer_ratio()
      return self

      and:

      cpython/Lib/fractions.py

      Lines 326 to 329 in 1812162

      elif (isinstance(number, float) or
      (not isinstance(number, type) and
      hasattr(number, 'as_integer_ratio'))):
      return cls._from_coprime_ints(*number.as_integer_ratio())

      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 infinite max_denominator - this should provide same value as as_integer_ratio() for Rational types and for some Real types (e.g. floating-point numbers). Though, in certain cases (e.g. for interval arithmetic) - infinite max_denominator doesn't make any sense.

    26. added a commit that references this issue on Nov 30, 2026
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    No one assigned

      Labels

      performancestdlibtype-feature

      Projects

      No projects

        Milestone

        No milestone

        Relationships

        None yet

        Development

        No branches or pull requests

        Issue actions