3 ms·
Does the new walrus := in python solve your problem?
by texaslonghorn5 4y ago
Does the new walrus := in python solve your problem?
- roelschroeven 4y agoThe official name is assignment expression, which can be good to know to find documentation. Here's the PEP: https://peps.python.org/pep-0572/ https://peps.python.org/pep-0572/
- otherme123 4y agoCuriously, searching the docs for "walrus" (https://docs.python.org/3/search.html?q=walrus https://docs.python.org/3/search.html?q=walrus) yields exactly the results you need, but searching for "assignment expression" yields the previous results mixed a lot of other results due to the word "expression".
- int_19h 4y agoNot really; where would you put it inside the []?
- dragonwriter 4y agoIn the example from the end of the earlier post: y for x in xs if (y:=x.ComputeSomething()).IsFoo and y.IsBar
- int_19h 4y agoI suppose that works, although readability is not great, to put it mildly.
- texaslonghorn5 4y agoMuch better would be [(y:=x.ComputeSomething()) for x in xs if y.IsFoo and y.IsBar]
- int_19h 4y agoThat doesn't work, because that first subexpression is evaluated last, after "if".
- ChadNauseam 4y agoFor another example of how to use the walrus operator, I use it multiple times in the code I linked a few comments up