Skip to content

PLR1701 fix is not safe (especially together with SIM114) #11616

@simonpercivall

Description

@simonpercivall

PLR1701 is mentioned in passing in #10245.

PLR1701 will merge repeated isinstance calls and also rewrite literal tuples into unions for modern Python versions. But an isinstance check with a variable bound tuple will also be merged into the union, and that will cause a TypeError at runtime.

This especially interacts badly with SIM114 where you could have defined two if arms, one with a variable bound tuple, and one with a literal tuple, and it'll get merged and wrongly rewritten as a union. Example below.

Ruff 0.45

pyproject.toml:

[tool.ruff]
target-version = "py311"

ruff check --select SIM114,PLR1701 --fix

TYPES = (dict, list)

if isinstance(None, TYPES):
    pass
elif isinstance(None, set | float):
    pass

actual

TYPES = (dict, list)

if isinstance(None, TYPES | set | float):
    pass

# Traceback (most recent call last):
#   File "PLR1701.py", line 3, in <module>
#     if isinstance(None, TYPES | set | float):
#                         ~~~~~~^~~~~
# TypeError: unsupported operand type(s) for |: 'tuple' and 'type'

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions