Open utterances-bot opened 2 years ago
Another example of using the walrus in a list comprehension: https://twitter.com/s_gruppetta_ct/status/1573284812248428545
The tweet says that the walrus is "needed" here, but it only seems needed if you force yourself to use a list comprehension; using a for loop or even using a list comprehension to build a list of turtles before operating on them with a for loop seems like it would be more idiomatic.
I think performing operations on the turtles inside the list comprehension is actually somewhat deceptive to the reader. When I see a list comprehension I expect it to be building up a list of values, which is why it can more clearly communicate intent than a loop in many cases. But in this case I first see it building a list of tuples of values, then I realise that most of those values are from method calls that return None, and then I see that all but the first item in each tuple is being discarded! A for loop would be more idiomatic to apply the actions to the turtles, as a for loop communicates to the reader that we're going to repeat some operations for each item in a list.
https://github.com/MarcoGorelli/auto-walrus is hilarious - especially the testimonials.
Suppose that big_func
is a computationally expensive function.
Which of the following do people prefer?
values = [big_func(item) for item in items if meets_condition(big_func(item))]
values = [output for item in items if meets_condition(output:=big_func(item))]
values = [output for item in items for output in [big_func(item)] if meets_condition(output)]
outputs = [big_func(item) for item in items]
values = [output for output in outputs if meets_condition(output)]
Option 2 is a little silly. Option 3 is my vote, but I am somewhat sympathetic to option 1.
I also like 3 - each part does one simple thing that is easy to reason about.
Seriously - can anyone come up with a compelling use case for the Walrus Operator? With examples like this you have to wonder: https://twitter.com/SourceryAI/status/1583096549936345088
Finally - a use for the walrus - for joke programming! auto-walrus. Genius! Thanks to Nathan for finding this gem.
The Walrus and the (Software) Carpenter | The When of Python Blog
The Walrus operator risks encouraging buggy code by conflating assignment with evaluation. PHP stands as a warning as to where this can lead. There are few cases where the convenience of the Walrus operator outweigh its risks and even these are not clear-cut. From a When of Python view, the Walrus operator should be in Deprecated Python, or possibly Situational Python but with very few situations accepted. The Walrus will only very occasionally belong in production code.
https://when-of-python.github.io/blog/the-walrus-and-the-software-carpenter.html