[Python-ideas] ('blue', 'red', 'orange' if something, 'green')
Chris Rebert
pyideas at rebertia.com
Mon Apr 25 06:20:55 CEST 2011
On Sun, Apr 24, 2011 at 8:34 PM, Nathan Schneider <nathan at cmu.edu> wrote:
> My expectation would be that
>
> foo = 'orange' if cond
>
> would be equivalent to
>
> foo = 'orange' if cond else None
Also equivalent:
foo = None
if cond: foo = 'orange'
> Has this shorthand been considered before? It seems natural to me, and
> I do find myself writing "else None" a lot, but from a (cursory)
> search I couldn't find any discussion of it.
>
> The only downside that comes to mind: conditionals in comprehensions
> would look the same but have different semantics, i.e.
>
> [x for x in bar if f(x)]
>
> might lead one to expect that None is added to the list wherever the
> condition fails.
Zen violations I perceive:
- Explicit is better than implicit.
Is writing the extra 2 4-letter words, and thus being perfectly
clear, really that burdensome?
- Special cases aren't special enough to break the rules.
- There should be one-- and preferably only one --obvious way to do it.
Down the route of adding trivial syntax sugar lies Perl.
- Errors should never pass silently.
Something that is currently a syntax error (leaving off the `else
foo` part of a ternary expression) would now be a valid expression,
possibly leading to subtle typo-related bugs. Admittedly, how frequent
this error is in practice is questionable.
Please avoid top-posting in the future.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-ideas
mailing list