comprehensions was Re: Switch statements again
Beni Cherniavsky
cben at techunix.technion.ac.il
Mon Jan 20 12:49:14 EST 2003
On 2003-01-19, Erik Max Francis wrote:
> Tim Peters wrote:
>
> > The prospects for a conditional operator are dim. Guido was
> > interested enough to implement it in late 2001, but eventually
> > rejected his own patch:
> >
> > http://www.python.org/sf/471421
>
> Pity that (and thanks for the reference). There is always hope, though;
> I seem to recall him at first being strongly opposed to adding bool to
> the language as well (which I also gladly welcomed). In fact, right
> from the start of using Python, a conditional operator and Booleans were
> the only tangible things I truly wished for.
>
Tim's comment there that a long chain of elif's would "cry out for a dict
lokkup" gave me another idea: instead of conditional operators, add "lazy"
dict/list literals. Curently you can also write a conditional opearator
as::
(lambda: g(), lambda:h())[bool(f())]()
or::
{True: lambda: h(), False: lambda: g()}[bool(f())]()
It's definitely not pretty! But if you could avoid repeating the
lambda inside, for example by putting it outside::
(lambda {True: h(), False: g()})[bool(f())]()
That's already better. The ``()`` in the end could go (getitem magic).
Then the front ``lambda`` syntax is not appropriate, which is a good
excuse for choosign a short one :-). The main remaining cruft is the bool
call. Luckily, in many cases the condition is something like ``x > 7``,
which always returns a bool (and I don't see a clean way to sneak an
automatic bool into it). Something like::
\{True: h(), False: g()}[x > 7]
is already good. The list/tuple case is less flexible and less readable
beacuse the false,true order is unnatural, so I think this can be limited
to dicts.
--
Beni Cherniavsky <cben at tx.technion.ac.il>
More information about the Python-list
mailing list