r/Python • • Nov 14 '17

Senior Python Programmers, what tricks do you want to impart to us young guns?

Like basic looping, performance improvement, etc.

1.3k Upvotes

629 comments sorted by

View all comments

Show parent comments

2

u/HellAintHalfFull Nov 14 '17

I don't necessarily disagree, but don't Python 3 best practices discourage the use of map, filter, and the like?

2

u/JayDepp Nov 14 '17

I'd say more that use of lambda is discouraged. If you've already got a function to do what you need, using map is more clearer than a comprehension. You don't need to scan through map(foo, bars) like you do in (foo(bar) for bar in bars) to see the intent. However, map(lambda bar: bar * 2, bars) is certainly unpythonic over a comprehension. Honestly, I think this is due to the design of the language. It's not a bad thing, but compare this to Kotlin which would use bars.map { it * 2 }, which is idiomatic in that language. Lambdas do have their place in python though, like in sorted(points, key=lambda p: p.x).

1

u/energybased Nov 14 '17

I don't agree with that. Comprehensions are the ideal in legibility even for the simplest case you have defined. People just aren't used to reading map.

1

u/Mattho Nov 15 '17

Even the map(int, foo)? That's perfect example of when to usemap in my opinion.

0

u/energybased Nov 15 '17

It's up to you. There's a reason the Google style guide advises against it and that's because everyone knows comprehensions, but not everyone can remember how map works, e.g., the order of the arguments.

3

u/JayDepp Nov 15 '17

To be fair, it does say that map is ok when you're not using a lambda.

https://google.github.io/styleguide/pyguide.html?showone=Deprecated_Language_Features#Deprecated_Language_Features

I've seen map in many languages, and I've only seen it as either xs.map(f) or map(f, xs), both of which are pretty logical (to me, at least).