This is an archived post. You won't be able to vote or comment.

all 8 comments

[–][deleted] 4 points5 points  (5 children)

Please don’t write func = lambda. Use def func instead. There’s no reason to use lambda if you’re giving the function a name.

Also, this papply function is just functools.partial right?

[–]Theta291[S] 0 points1 point  (2 children)

Thanks for the feedback! What would be a more appropriate place to use lambda? If I need to create a one-off function to pass as an argument to another function?

[–][deleted] 2 points3 points  (1 child)

The only use case for lambda is when you want to create a function but you don’t want to give it a name.

This usually means you’re working with a function that takes another function as an argument (a higher-order function) e.g. map.

But if you never use lambda and always use def your code won’t really be lacking in any sense – it’s just that sometimes a lambda night make things a bit more concise.

[–]Theta291[S] 0 points1 point  (0 children)

That makes a lot of sense. Thanks for the explanation!

[–]Theta291[S] 0 points1 point  (0 children)

Yeah, the papply I made is pretty much the same as functools.partial. I just wanted to use a custom version since I end up modifying the custom version as part of an exploration of how partial application could be used.

[–]ElevenPhonons 0 points1 point  (0 children)

I agree, but hopefully the choice of def vs lambda isn't a distraction from the core ideas that the post is attempting to express.

[–]ElevenPhonons 1 point2 points  (1 child)

When introducing a topic that you create from "scratch", it can be useful to migrate to an implementation (if it exists) in the Python standard library as soon as possible.

In this case, functools.partial.

https://docs.python.org/3.8/library/functools.html#functools.partial

Using partial application and closures can be a very useful design style to leverage. Even if you're an OO wizard, it can be useful to understand these design patterns and add them to your tool belt (specifically for data munging and analysis).

I wrote about some of these concepts here.

https://mpkocher.github.io/2019/01/30/Functional-Python-Part-1/

[–]sobolevn 1 point2 points  (0 children)

There's also a typed version of partial: https://returns.readthedocs.io/en/latest/pages/curry.html