xHalcyonx
xHalcyonx

Reputation: 61

Need help rewriting a Python function without using lambda

Basically I just want to know what this piece of code will look like if the lambda wasn't used.

bttn_0 = Button(calc, text = "0")

bttn_0["command"] = lambda: sum1.num_press(0)

bttn_0.grid(row = 4, column = 1, pady = 5) 

I know it will start of as def something but I'm pretty lost in terms of what will go where. You may wonder WHY I'm asking this. Well I'm trying to figure out the use of lambda and how to use it more efficiently in my coding but I first need to know how to implement it from a original def function without lambda. I hope this makes sense. I am aware that lambda is the quickest method but as I said, I'm still interested in learning about simplifying my coding and will need the original way to do it before I can get fancy.

Thanks for the help!

Upvotes: 1

Views: 270

Answers (2)

atlasologist
atlasologist

Reputation: 3964

Consider these two examples:

Without the lambda expression, if you wanted to print numbers (for example), you'd need a different function for each Button:

def number_0():
    print 0

def number_1():
    print 1

Button(calc, text='0 named function', command=number_0).pack()
Button(calc, text='1 named function', command=number_1).pack()

However, with the lambda expression, you can pass an argument from the Button, and you can greatly reduce the number of lines in your code:

def num_press(n):
    print n

Button(calc, text='0 with lambda', command=lambda: num_press(0)).pack()
Button(calc, text='1 with lambda', command=lambda: num_press(1)).pack()

Upvotes: 1

Erik Kaplun
Erik Kaplun

Reputation: 38217

Your only meaningful other option is passing a named function:

def command_handler():
    return sum1.num_press(0)  # or without the return

bttn_0["command"] = command_handler

but there is no difference there, and the lambda looks much better in my opinion (although some people prefer to avoid them for whatever reasons of style or taste) — you need to pass a callable, and the only way to define a callable is a lambda or a function.

A third option, technically speaking, is an object with a __call__ method but that's by far an overkill here, so I'm only demonstrating it for completeness' sake:

class CmdHandler(object):
    def __call__(self):
        return sum1.num_press(0)

bttn_0["command"] = CmdHandler()

Upvotes: 2

Related Questions