I've been diving into PEP8 guidelines and noticed it advises against using lambda expressions assigned to variables. It suggests that we should always use a def statement instead. I'm wondering if the Python interpreter treats these two methods the same or if there's a difference beyond just style. My inclination is that there's a stylistic difference, especially in scenarios where I might want to define a function quickly, like with `f = lambda x: x**2` instead of using `def f(x): return x**2`. My thought is that if a function meets criteria like being called in nearby scopes or if it has free variables, a lambda could seem more appropriate, even if it compiles to the same bytecode. However, I'm curious whether this perspective is valid or if it conflicts with Pythonic principles. I've also noticed that type hinting with lambdas can get messy, which detracts from the lightweight feel they're supposed to provide.
5 Answers
If you're naming your functions, definitely go with `def`. It brings clarity and is the standard way of doing things in Python. Lambdas should be for quick, unnamed functions. Trying to force them into something they're not isn't really necessary.
It's not entirely the same. When you define a function with `def`, it gets an actual name, which can be useful for debugging and introspection. For instance, `foo.__name__` gives 'foo', while a lambda will just show up as ''. This can matter for error messages and other situations where you need to understand what's happening.
I've found that once a function starts getting reused, it's usually better to go with the PEP8 style of using `def f(x)` to keep everything clear and hidden when possible. Lambdas are best suited for single-use cases, like when you need a quick callback in a map or filter function.
I hear you about feeling like there's a distinction. But when it comes to type hints and documentation, lambda can be cumbersome. Try adding type hints to a lambda, and you'll see how messy it can get compared to a regular function. It's just easier and cleaner to use `def` in more complex situations.
Using lambda expressions as if they're functions can feel weird because they're meant for more temporary tasks. It's okay to name functions with `def`, but when you name a lambda, it sort of defeats the purpose of its simplicity and syntactic sugar.

I see your point, but I still think the essence of a lambda expression helps keep the code concise in certain cases. It's all about balance, right?