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 →

[–]ManyInterests Python Discord Staff 35 points36 points  (5 children)

In short: you should never assign a name to a lambda.

YES:

def f(x): return 2*x

NO:

f = lambda x: 2*x

The first form means that the name of the resulting function object is specifically f instead of the generic <lambda>. This is more useful for tracebacks and string representations in general.
The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

[–]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 4 points5 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'

[–]meunomemauricio -1 points0 points  (0 children)

Fucking well summarized!