[Python-ideas] why not "name = value if condition"?
steve at pearwood.info
Tue Apr 7 15:38:21 CEST 2009
On Tue, 7 Apr 2009 11:03:41 pm spir wrote:
> 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:
is invalid -- you need to have a value to bind to the name.
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
if fileName is None: fileName = title+".py"
More information about the Python-ideas