Code: Select all
def foo(bar):
print((1, 2) if bar else 3, 4)
The workround is simply to make 3, 4 a tuple.
Code: Select all
def foo(bar):
print((1, 2) if bar else 3, 4)
Code: Select all
print(((1, 2,) if bar else 3), 4)
Code: Select all
print((1, 2,), 4) # (1, 2) 4
or
print(3, 4) # 3 4
As far as I can tell, it's interpreted as the argument separator for the call to print() in both cases?pythoncoder wrote: ↑Wed Aug 14, 2019 5:22 amThe parser's interpretation of the comma between 3, 4 evidently depends on the state of bar. Is this really to be expected?
Code: Select all
>>> bar = False
>>> z = (1, 2) if bar else 3, 4
>>> z
(3, 4)
>>> bar = True
>>> z = (1, 2) if bar else 3, 4
>>> z
((1, 2), 4)
>>>
Right, in this case it's the separator for a tuple expression. But the parser still handles the comma the same way, regardless of the value of bar. It's the same as:
Code: Select all
>>> bar = False
>>> x = (1, 2) if bar else 3
>>> z = x, 4
>>> z
(3, 4)
>>> bar = True
>>> x = (1, 2) if bar else 3
>>> z = x, 4
>>> z
((1, 2), 4)
>>>