amontalenti / elements-of-python-style

Goes beyond PEP8 to discuss what makes Python code feel great. A Strunk & White for Python.
3.44k stars 260 forks source link

map/filter vs comprehensions. #3

Closed coady closed 8 years ago

coady commented 8 years ago

I think it's universally agreed that comprehensions are preferred over map/filter with lambda. There seems to be momentum on the side of omitting with lambda and implying in general . And there's a history there. The given example has an unnecessary lambda, so that could be worth being explicit about.

# bad
 filter(lambda x: len(x) > 0, map(myfunc, some_list))

 # good
 [myfunc(x) for x in some_list if len(x) > 0]

It could just be filter(len, for filter(None,.

coady commented 8 years ago

Trying to remain neutral :), but this is actually a perfect example to drill-down on. Because it's buggy: the map and filter operations are reversed. It's one thing to propose

map(myfunc, filter(None, some_list))

is less readable than

[myfunc(x) for x in some_list if x]

But it's something else entirely to propose

filter(None, map(myfunc, some_list))

is less readable than

[x for x in [myfunc(x) for x in some_list] if x]
amontalenti commented 8 years ago

@coady Indeed, you are right. Shame on me for not testing this example!

What is your suggestion? Fix the bug (by reversing operations in map/filter case) or change the rule and example?

dchudz commented 8 years ago

I'd vote for changing the rule (only avoid map/reduce if they require lambdas) and the example.

amontalenti commented 8 years ago

I fixed the bug and changed the example slightly so that it couldn't be replaced by filter(None.

@coady I'm thinking of adding a qualifier to the example that says, "though you should prefer comprehensions for most of the simple cases, there are occasions where map() or filter() will be more readable, so use your judgment."

coady commented 8 years ago

Sounds good to me.