BrowserM
BrowserM

Reputation: 61

Storing function name in dictionary and returning function name with parameters

def add(op1,op2):
    return op1 + op2

def sub(op1,op2):
    return op1 - op2

def mul(op1,op2):
    return op1 * op2

def div(op1,op2):
    return op1 / op2



def evaluate(op1,operator,op2):
    ops = {'+':add,'-':sub,'*':mul,'/':div}
    return ops[operator](op1,op2)

print(evaluate(1,'/',2))

>>> 0.5

I was messing around with dictionaries and I got this idea of storing a function name as a value and then returning that function name with parameters. I was surprised to see it actually worked. I don't know how this is possible and what's going on behind the scenes so can someone explain to me what exactly is happening in this piece of code in detail?

Upvotes: 2

Views: 926

Answers (2)

U13-Forward
U13-Forward

Reputation: 71610

To Explain:

  • The first four functions are making operator functions

  • Then in the evaluate function, it creates a dictionary, with the signs as key, and the functions as values

  • Then, get the operator argument, which is one of the signs, so get the value of the key:value pair when the key is that sign, then you just call that value since it's a function

Note that there's a better code, actually operator module contains the first four functions already.

The code for that:

from operator import add,sub,mul,truediv
def evaluate(op1,operator,op2):
    ops = {'+':add,'-':sub,'*':mul,'/':truediv}
    return ops[operator](op1,op2)

print(evaluate(1,'/',2))

Output:

0.5

Upvotes: 1

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

If you're experienced in C or C++, then you'll be aware of the idea of "function pointers" - you take the memory address of a function, put it in a variable, and then later execute "the function at that memory address". It's pretty much the same in python.

Essentially, python treats a function as its own type of object:

>>> def x():
...     print("Hello World")
... 
>>> type(x)
<class 'function'>

A function can be called with the parentheses operators, obviously. However, since a function is also an object, you can put that function inside of a variable:

>>> y = x
>>> y()
Hello World

What you're doing with the dict is making key-value pairs: "+" corresponds to the object add; and since add is a function, it can be called.

Upvotes: 1

Related Questions