For review: PEP 308 - If-then-else expression
holger krekel
pyth at devel.trillke.net
Fri Feb 7 14:47:09 EST 2003
Andrew Koenig wrote:
> holger> What about a missing else clause? e.g.
>
> holger> <expression> if <condition>
>
> holger> Allowing it could be nice for stuff like
>
> holger> result = obj(...) if callable(obj)
>
> It's supposed to be an expression that yields a value.
> So your example would be equivalent to
>
> result = (obj(...) if callable(obj))
>
> and the question is: What is the value of (x if y) when y is false?
sorry, i also got private mail about this. I intended
to say that
result = obj() if callable(obj)
should indeed set the result to None if the condition evalutes
to false. I don't think there is any other sensible result
other than 'None'. But of course,
result = obj() if callable(obj) else None
would be more explicit. The question is whether my suggestion
has enough use cases and is thus practical enough. I sometimes
have the equivalent of this situation:
result = obj.method(...) if someconditionalexpr(obj)
if result is None:
# either we don't have such a method or
# calling it returned None
writing it today, you'd have to say either
result = someconditionalexpr(obj) and obj.method(...) or None
if result is None:
...
which is a bit tricky to understand (and results in long lines).
Or you could write
try:
result = obj.method(...)
except AttributeError:
result = None
if result is None:
# either we don't have such a method or
# calling it returned None
or
result = getattr(obj, 'method')
if result is not None:
result = obj.method(...)
if result is None:
# either we don't have such a method or
# calling it returned None
but none of these solutions reads too well. The current
constructs are an rather 'indirect' way to express this
use case.
However, i fear that the PEP might decrease python's readability
and i am currently not leaning towards one way or the other.
regards,
holger
More information about the Python-list
mailing list