Przemysław Krawczyk
Przemysław Krawczyk

Reputation: 25

Why I need to use this bracket after get function?

I have a problem with understanding this code:

def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)() # here I don't understand this brackets  
                                    #  after closing get function

print(dispatch_dict('sub', 2, 4))

Upvotes: 0

Views: 74

Answers (2)

jbet
jbet

Reputation: 492

Your .get(operator, lambda: None) returns function object - read e.g. https://medium.com/python-pandemonium/function-as-objects-in-python-d5215e6d1b0d, and adding () calls the function.

Maybe this simplification will help:

def add_lambda(x, y):
    add = lambda: x + y  # Note this is not PEP-8 compliant
    return add

the_function = add_lambda(31, 11)  # returns lambda function
the_function()  # here are your brackets, this returns 42

Upvotes: 1

vurmux
vurmux

Reputation: 10030

.get() function returns you lambdas (from the dict or just empty lambda). Lambda is an anonymous function so .get() returns you a function. These brackets are needed to return you the result of this function instead of the function itself because with them the function is calling and returning you the result.

Upvotes: 1

Related Questions