[Python-ideas] ('blue', 'red', 'orange' if something, 'green')

Nathan Schneider nathan at cmu.edu
Mon Apr 25 05:34:23 CEST 2011


My expectation would be that

  foo = 'orange' if cond

would be equivalent to

  foo = 'orange' if cond else None


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.


Nathan

On Sun, Apr 24, 2011 at 10:03 PM, Westley Martínez <anikom15 at gmail.com> wrote:
>
> On Mon, Apr 25, 2011 at 01:18:17AM +0200, Sturla Molden wrote:
> > Den 23.04.2011 21:36, skrev Westley Martínez:
> > >No. This is a horrible idea.
> >
> > Do you think so?  ;-)
> >
> > The most "beautiful" thing with this syntax is this:
> >
> > After typing
> >
> >     foo = 'orange' if cond
> >
> > or
> >
> >     foo = 'orange' if cond else pass
> >
> > we don't know if accessing foo will raise a NameError or
> > not (not without checking cond that is). And we all know
> > what an uncaught exception might do (cf. Ariane 5).
> >
> >
> > Sturla
> >
> >
>
> Right, the point of the else part of if/else statement is so we can
> guarantee that foo is defined.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas



More information about the Python-ideas mailing list