[Python-ideas] why not "name = value if condition"?
greg.ewing at canterbury.ac.nz
Wed Apr 8 00:38:02 CEST 2009
> What's the reason why
> name = value if condition
> is invalid?
> Sure, one can write
> if condition:
> name = value
The 'a if b else c' construct is an expression. The
transformation you want can't be implemented by treating
it as an expression, since you want the 'if' to apply
to the assignment, not just the RHS.
> but the rationale in favour of, or against, a one-liner shortcut
> is the same as for the ternary case (with else).
No, it's not. The ternary case can be used as an
expression anywhere, often saving an assignment to
an intermediate variable. And when used with an
assignment, it avoids repeating the LHS, i.e.
a = b if c else d
as opposed to
a = c
a = d
Your proposed shortcut doesn't save anything except
a small amount of whitespace, so the justification
is much weaker.
More information about the Python-ideas