Consider:
>>> def foo(x, y=23):
... print x, y
...
>>> data = (1, 2)
>>> foo(*data if data else data)
1 2
>>> data = None
>>> foo(*data if data else data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() argument after * must be a sequence
>>>
Ok, * binds tighter than if else, so add the parens to fix this:
>>> foo((*data) if data else data)
File "<stdin>", line 1
foo((*data) if data else data)
^
SyntaxError: invalid syntax
>>>
The parser thinks I'm trying to use the *tuple syntax inside a tuple
in an argument list - at least, that's what I think it is flagging as
invalid syntax. But that's not what I'm doing! Wrapping parens around
an expression doesn't automatically turn it into a tuple, even in an
argument list:
>>> foo((1))
1 23
>>>
This looks like a parser bug to me. However, the interactions of the
various things one can put in argument lists have gotten complex
enough that it's hard to say for sure. If it's not a bug, it should
probably be documented somewhere.
For the record, the workaround is:
>>> foo(*data if data else (data,))
None 23
>>>
And yes, that last comma is required, otherwise you're back to the
first error.
|