This comes up pretty often.  Every example can be replaced by a loop over a
single item list. It's a bit idiomatic, but not difficult.  Many, as you
note, can use the new walrus operator instead.

[price for price in [item.get('price')] for item in basket if price is not
None]


On Mon, Jul 15, 2019 at 10:21 AM Fabrizio Messina <[email protected]>
wrote:

> Hello,
>
> It is likely not the first time such a proposal is being made but let's
> see.
> I would like to explicitly set variable names in list comprehensions using
> a where keyword, eventually set after the if keyword:
>
> [price for item in basket if price is not None where price := item.get(
> 'price')]
>
> For this example one could use the walrus operator which is indeed
> smaller:
> [price for item in basket if price := item.get('price') is not None]
>
> But I fell that this approach is a bit opportunistic as one is doing two
> things at a time, if you allow me more lines for a somewhat more complex
> example:
>
> [
>     price * (1 + vat)
>     for
>         item in basket
>     if
>         price is not None
>     where
>         price := item.get('price')
>         vat := get_vat(item, user)
> ]
>
> Now this example may look pretty stupid and probably one may simply use
> for loop, but I feel that this kind of Haskell-like where inside of list
> comprehension will let the programmer have a space where they can
> explicitly state the variables.
>
> Best regards,
> Fabrizio
> _______________________________________________
> Python-ideas mailing list -- [email protected]
> To unsubscribe send an email to [email protected]
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/[email protected]/message/AHI6NIMZNFVL2ROW6CD2HFBAPL7KCSW7/
> Code of Conduct: http://python.org/psf/codeofconduct/
>


-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/CG3IQZUX6QSMQII5OVOQAHRV2W735N4Z/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to