5 ms·
Though it doesn't take that much of an effort to just name your callback function and pass it as an argument. Python functions are first-class "objects" that ca
by Zopieux 8y ago
Though it doesn't take that much of an effort to just name your callback function and pass it as an argument. Python functions are first-class "objects" that can be passed around, use them!
I've always found Python lambdas to be uncanny, weird and error prone. It's kinda syntactic sugar for expression-only defs with counterintuitive scope rules. I would recommend just not using them and fall back to named functions. It's just one extra line and that way you get to name it, which is always a nice thing.
- saagarjha 8y agoThis is extremely heavyweight syntax for something I like to use as a lightweight construct. If I wanted a function, I would make something a function.
- dontreact 8y agox = lambda y: <code goes here> def x(y): <code goes here> What's so heavyweight? A new line and a tab?
- lou1306 8y agoIMO lambdas are useful because they reduce mental overhead by allowing the developer not to give names to trivial functions [1]. Compare these two equivalent pieces of code: youngest_person = min(people, key=lambda x: x.age) def get_age(x): return x.age youngest_person = min(people, key=get_age) This may not seem like a huge difference, but using lambdas scales better. [1] Incidentally, this is the same reason why I don't miss multi-line lambdas (in Python): multi-line functions are seldom trivial.
- dontreact 8y agoYeah in the context of multi line functions the overhead is A new line A tab A return This does not sound heavyweight to me (in that context). In the context of a single line function I see the utility of lambdas.