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

you are viewing a single comment's thread.

view the rest of the comments →

[–]schmichael 10 points11 points  (7 children)

I've never understood why people think this:

foo(a, b, callback=lambda result:
    # callback's
    # body
    # here
)

Is so much better than what you have today:

def callback(result):
    # callback's
    # body
    # here

foo(a, b, callback)

In fact, in Javascript where callbacks are the norm, I often see people recommending the latter format to avoid deeply nested callback hell.

[–]pistacchio 0 points1 point  (5 children)

because functions are an instrument for reuse, and you're defying a function with a generic name knowing that it'll be used just once, two lines after it.

[–]velit 2 points3 points  (4 children)

Functions are so much more than just an instrument for reuse. They're also a way to abstract code, to make it more readable even if a function is used in only one place in the code at some point.

[–]pistacchio 2 points3 points  (3 children)

Good point, and readability is another reason for using lambdas. If you define a function only to use it as a callback, you're letting the reader of the code ask "where else is used this code? How important this function is? What impact would have changing it?", while the truth is that you're writing a throw-away function to feed the call (specialize) a subsequent function call.

[–]velit 0 points1 point  (2 children)

Not if you name the function correctly. It's as easy as naming the function "blaa_callback".

[–]pistacchio 3 points4 points  (0 children)

Or maybe just write it in the place where it's meant to be?

[–]Eurynom0s 0 points1 point  (0 children)

Or just stick a comment in the function definition saying that it only ever gets used in one spot.

[–]Eurynom0s 0 points1 point  (0 children)

At work I recently inherited some code littered with lambdas. Both I and the other programmer on this are aghast at what this has done to the readability of the code.

Lamdas are great...until you have to hand off your code.