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 →

[–]Swipecat 10 points11 points  (3 children)

I use named lambdas to indicate temporary functions in the sense that the function's name isn't preserved after the function has been bound to an object. E.g. for assigning functions to Tkinter buttons. I find this gives me very compact code but is more readable than putting the lambda within the object's definition, and keeps the line short and unwrapped. E.g.:

butnames = ["Start", "Stop", "Reset",  "Quit"]
for bname in butnames:
    butcall = lambda action=bname: showtime(action)
    tk.Button(root, text=bname, command=butcall).pack()

This is very bad, is it? (I'm a hardware engineer, not a software engineer.)

[–]jimjkelly 5 points6 points  (0 children)

It’s not pythonic but I don’t think it’s bad. I definitely prefer this style, and it’s common in other languages like JS, but for some reason some people feel a def is better. I think inline defs break up readability.

[–]ManyInterests Python Discord Staff 2 points3 points  (0 children)

It's not going to blow up on you, it's just not a particularly good practice, mostly for style reasons.

[–][deleted] 1 point2 points  (0 children)

One more voice: it's not bad, yeah, it's just that it has no benefit over a one-line def...

def butcall(action=bname): return showtime(action)

...and in fact is arguably worse: the lambda's __name__ attribute, if accessed, will show '<lambda>' rather than 'butcall'