[Python-ideas] why not "name = value if condition"?

Steven D'Aprano steve at pearwood.info
Tue Apr 7 15:38:21 CEST 2009


On Tue, 7 Apr 2009 11:03:41 pm spir wrote:
> Hello,
>
> What's the reason why
>    name = value if condition
> is invalid? Meaning: there _must_ be an else clause.


Because "value if condition else other" is an expression, not a 
statement, and thus *must* have a value.

    name = value if condition

only has a value sometimes, and so is invalid for the same reason that:

    name = 

is invalid -- you need to have a value to bind to the name.

    if condition:
        name = value

is different. If condition is false, the branch "name = value" isn't 
taken at all. The entire block isn't an expression, so it doesn't have, 
or need, a value.


> [I imagine this has been discussed and refused consciously, but I
> couldn't find it in PEP308, nore in archives.]
>
> It would be practicle in many situations, e.g. to give default values
> to parameters:
>
> def writeFile(text, title, format=STANDARD, fileName=None):
>    fileName = title+".py" if fileName is None

Maybe so, but this can just as easily be written:

    if fileName is None:
        fileName = title+".py"

And if you're concerned about this being a two-liner (perhaps because 
the Enter key on your keyboard is broken *wink*) you can write it as a 
one-liner:

    if fileName is None: fileName = title+".py"


-- 
Steven D'Aprano



More information about the Python-ideas mailing list