0

I'd like to introduce assignment expressions in my code where possible but I've stumbled upon a very simple case I didn't find an example for:

Given a very common example

[(y := f(x), x/y) for x in some_iterable]

I wonder how to not use y directly, e.g. I only want x/y and y/x.

In a more realistic example I would currently write

[(obj.elem1, obj.elem2) for x in some_iterable for obj in (f(x),)]

which is not very intuitive but the only way I know to mimic a let or where semamtic.

Is there some way to say

[(obj.elem1, obj.elem2) where obj := f(x) for x in some_iterable]

?

Edit:

One very obvious way would be to write

[((obj := f(x)).elem1, obj.elem2) for x in some_iterable]

but this is hard to read in my eyes. I'd rather have a way to still write (obj.elem1, obj.elem2) and move the assignment out of the tuple.

frans
  • 6,905
  • 8
  • 40
  • 95
  • Your function could return an iterator. Something like `[(obj.a, obj.b) for obj in my_iter(some_iterable)]`and where `my_iter` looks like `for x in some_iterable: yield f(x)`. Did this help you ? – Adrien Kaczmarek Sep 30 '20 at 15:49
  • My question is more about the assignment expression syntax. So your answer is correct but it's not exactly what I'm looking for – frans Oct 01 '20 at 09:52

0 Answers0