mirror of
https://github.com/astral-sh/ruff.git
synced 2025-10-27 18:36:23 +00:00
Format ExprIfExp (ternary operator) (#5597)
## Summary
Format `ExprIfExp`, also known as the ternary operator or inline `if`.
It can look like
```python
a1 = 1 if True else 2
```
but also
```python
b1 = (
# We return "a" ...
"a" # that's our True value
# ... if this condition matches ...
if True # that's our test
# ... otherwise we return "b§
else "b" # that's our False value
)
```
This also fixes a visitor order bug.
The jaccard index on django goes from 0.911 to 0.915.
## Test Plan
I added fixtures without and with comments in strange places.
This commit is contained in:
parent
0f9d7283e7
commit
0b9af031fb
9 changed files with 328 additions and 212 deletions
33
crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/if.py
vendored
Normal file
33
crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/if.py
vendored
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
a1 = 1 if True else 2
|
||||
|
||||
a2 = "this is a very long text that will make the group break to check that parentheses are added" if True else 2
|
||||
|
||||
# These comment should be kept in place
|
||||
b1 = (
|
||||
# We return "a" ...
|
||||
"a" # that's our True value
|
||||
# ... if this condition matches ...
|
||||
if True # that's our test
|
||||
# ... otherwise we return "b"
|
||||
else "b" # that's our False value
|
||||
)
|
||||
|
||||
# These only need to be stable, bonus is we also keep the order
|
||||
c1 = (
|
||||
"a" # 1
|
||||
if # 2
|
||||
True # 3
|
||||
else # 4
|
||||
"b" # 5
|
||||
)
|
||||
c2 = (
|
||||
"a" # 1
|
||||
# 2
|
||||
if # 3
|
||||
# 4
|
||||
True # 5
|
||||
# 6
|
||||
else # 7
|
||||
# 8
|
||||
"b" # 9
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue