List Comprehensions For Side Effects - Idiomatically Correct Or An Abomination?
Solution 1:
List comprehensions are for creating a list. That's not what you're doing here, so I'd avoid it.
Solution 2:
Personally, I would do
for cheese in cheeses:
cheese.out_of_stock()
This feels a bit more explicit to me. It's another line, but I suspect that another programmer reading that code would understand it well, whereas the list comprehension version might be slightly confusing. In addition, I could imagine that someone else might come along later (not knowing that out_of_stock
doesn't return a value) and try to use that list later.
I guess there's nothing wrong with it, though. Ultimately, it comes down to who's going to be reading that code later (yourself or others) and whether or not they'll know what's going on.
EDIT: Also, you're using a lovely functional programming construct taken from Haskell to do nasty stateful things...
Solution 3:
Semantically, if cheese.out_of_stock returned a boolean, then it would be fine. However this is not very recommended if cheese.out_of_stock does not return a value, then it would be very confusing and unmaintainable.
importthis
for more information
Solution 4:
List comprehensions are usually used for filtering (or something similar where the result of the comprehsion is being used later) but not for replacing a loop calling a method on the iteration data. So this works but it locks ugly.
Solution 5:
If you are doing something with the return values of cheese.out_of_stock()
this is perfectly Pythonic. If you are discarding the result of the list comprehension, it is bad style.
Creating the list is a waste of time and memory, just use the two line for
loop from Peter's answer
Post a Comment for "List Comprehensions For Side Effects - Idiomatically Correct Or An Abomination?"