Skip to content

C413 fix for reversed(sorted(..., reverse=...)) needs parentheses when key is a boolop to avoid changing semantics #10335

@jakkdl

Description

@jakkdl
reversed(sorted([1, 2, 3], reverse=False or True)) # reverses twice -> 1, 2, 3
# ruff C413 autofixes the above line to the below
sorted([1, 2, 3], reverse=not False or True) # reverses once -> 3, 2, 1
# if a paren were to be added, the problem is resolved
sorted([1, 2, 3], reverse=not (False or True)) # doesn't reverse -> 1, 2, 3

Due to https://docs.python.org/3/reference/expressions.html#operator-precedence
This affects boolean operators and if-expr's. Higher-precedented operators won't need parens added, walruses need to be wrapped in parens in the original statement, and lambda's are invalid in this context.

command invocation & version

$ ruff check --select=C413 --fix --unsafe-fixes --isolated - <<< 'reversed(sorted([1, 2, 3], reverse=True if True else False))' 
sorted([1, 2, 3], reverse=not True if True else False)
Found 1 error (1 fixed, 0 remaining).
$ ruff --version
ruff 0.3.2

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingfixesRelated to suggested fixes for violationshelp wantedContributions especially welcome

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions