Skip to content

Confused traceback while floordiv or mod happens between Fraction and complex objects #102840

Closed
@Eclips4

Description

@Eclips4
from fractions import Fraction
a = Fraction(1, 2)
b = a // 1j
>
Traceback (most recent call last):
  File "C:\Users\KIRILL-1\CLionProjects\cpython\example.py", line 5, in <module>
    b = a // 1j
        ~~^^~~~
  File "C:\Users\KIRILL-1\AppData\Local\Programs\Python\Python311\Lib\fractions.py", line 363, in forward
    return fallback_operator(complex(a), b)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported operand type(s) for //: 'complex' and 'complex'

This traceback really confused me.
However, it's easy to fix, just need change these lines:

cpython/Lib/fractions.py

Lines 620 to 621 in 5e6661b

elif isinstance(b, complex):
return fallback_operator(complex(a), b)

To this:

elif isinstance(b, complex):
    try:
        return fallback_operator(complex(a), b)
    except TypeError:
        raise TypeError(
            "unsupported operand type(s) for %r: %r and %r" % (
                fallback_operator.__name__,
                type(a).__qualname__,
                type(b).__qualname__)
        ) from None

So, after that, we have a pretty nice traceback:

Traceback (most recent call last):
  File "C:\Users\KIRILL-1\CLionProjects\cpython\example.py", line 5, in <module>
    b = a // 1j
        ~~^^~~~
  File "C:\Users\KIRILL-1\CLionProjects\cpython\Lib\fractions.py", line 624, in forward
    raise TypeError(
TypeError: unsupported operand type(s) for 'floordiv': 'Fraction' and 'complex'

But, here a one problem - would be nice to have in traceback originally // instead of floordiv. I have no idea how to do it, without create a mapping with names. Theoretically - we can add a special attribute for it in operator, but it should be a another discussion.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions