Adding where keyword inside list coprehensions

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

On 15/07/2019 16:18, Fabrizio Messina wrote:
This is what assignment expressions (PEP 572) are for (https://www.python.org/dev/peps/pep-0572/). Personally I would have preferred something much more limited like your keyword, but that argument was lost a long time ago now. -- Rhodri James *-* Kynesim Ltd

On Mon, Jul 15, 2019 at 08:18:30AM -0700, Fabrizio Messina wrote:
Since vat is only used once, we don't need a named variable for it: [price * (1 + get_vat(item, user)) for item in basket if (price:=item.get('price')) is not None ] But if you insist in naming it: [price * (1 + vat:= get_vat(item, user)) for item in basket if (price:=item.get('price')) is not None ] -- Steven

On 15/07/2019 16:18, Fabrizio Messina wrote:
This is what assignment expressions (PEP 572) are for (https://www.python.org/dev/peps/pep-0572/). Personally I would have preferred something much more limited like your keyword, but that argument was lost a long time ago now. -- Rhodri James *-* Kynesim Ltd

On Mon, Jul 15, 2019 at 08:18:30AM -0700, Fabrizio Messina wrote:
Since vat is only used once, we don't need a named variable for it: [price * (1 + get_vat(item, user)) for item in basket if (price:=item.get('price')) is not None ] But if you insist in naming it: [price * (1 + vat:= get_vat(item, user)) for item in basket if (price:=item.get('price')) is not None ] -- Steven
participants (3)
-
Fabrizio Messina
-
Rhodri James
-
Steven D'Aprano