This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: conditional expressions vs. () and * in call arguments.
Type: Stage:
Components: Interpreter Core Versions: Python 2.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: georg.brandl, mwm
Priority: normal Keywords:

Created on 2007-06-26 15:18 by mwm, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg32399 - (view) Author: Mike Meyer (mwm) Date: 2007-06-26 15:18
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.
msg32400 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2007-06-26 16:51
Sorry, I can't see a problem here.

"data if data else data" is nonsensical and equivalent to "data". This of course doesn't work since None is not a sequence.
Thus, your "workaround" is the correct solution.
History
Date User Action Args
2022-04-11 14:56:25adminsetgithub: 45130
2007-06-26 15:18:53mwmcreate