Skip to content

RUF032 fix can produce strings that are invalid for Decimal #13258

@dscorbett

Description

@dscorbett

RUF032 produces an invalid string argument when the existing argument is a float with multiple unary operators. Decimal’s string parser only accepts one sign character.

$ ruff --version
ruff 0.6.4
$ cat ruf032.py
from decimal import Decimal
Decimal(++0.3)
$ ruff check --isolated --preview --select RUF032 ruf032.py --unsafe-fixes --fix
Found 1 error (1 fixed, 0 remaining).
$ python ruf032.py 2>&1 | tail -n 2
    Decimal("++0.3")
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

RUF032 also stringifies the argument if it is a float with the ~ unary operator. Applying ~ to a float raises a TypeError and should never happen, but if someone does write that, it is probably not helpful to convert it to a string, which makes it raise a different error that the surrounding code might not be expecting.

$ cat ruf032_error.py
from decimal import Decimal
Decimal(~1.0)
$ python ruf032_error.py 2>&1 | tail -n 3
    Decimal(~1.0)
            ^^^^
TypeError: bad operand type for unary ~: 'float'
$ ruff check --isolated --preview --select RUF032 ruf032_error.py --unsafe-fixes --fix
Found 1 error (1 fixed, 0 remaining).
$ python ruf032_error.py 2>&1 | tail -n 2
    Decimal("~1.0")
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfixesRelated to suggested fixes for violationshelp wantedContributions especially welcomepreviewRelated to preview mode features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions