Home > OS >  How would I run a function given its name?
How would I run a function given its name?

Time:10-17

I have a large number of blending functions:

mix(a, b)
add(a, b)
sub(a, b)
xor(a, b)
...

These functions all take the same inputs and provide different outputs, all of the same type. However, I do not know which function must be run until runtime.

How would I go about implementing this behavior?

Example code:

def add(a, b):
    return a   b

def mix(a, b):
    return a * b

# Required blend -> decided by other code
blend_name = "add"
a = input("Some input")
b = input("Some other input")

result = run(add, a, b)  # I need a run function

I have looked online, but most searches lead to either running functions from the console, or how to define a function.

CodePudding user response:

I'm not really big fan of using dictionary in this case so here is my approach using getattr. although technically its almost the same thing and principle is also almost the same, code looks cleaner for me at least

class operators():
    def add(self, a, b):
        return (a   b)

    def mix(self, a, b):
        return(a * b)


# Required blend -> decided by other code
blend_name = "add"
a = input("Some input")
b = input("Some other input")
method = getattr(operators, blend_name)
result = method(operators, a, b)
print(result) #prints 12 for input 1 and 2 for obvious reasons

EDIT this is edited code without getattr and it looks way cleaner. so you can make this class the module and import as needed, also adding new operators are easy peasy, without caring to add an operator in two places (in the case of using dictionary to store functions as a key/value)

class operators():

    def add(self, a, b):
        return (a   b)

    def mix(self, a, b):
        return(a * b)

    def calculate(self, blend_name, a, b):
        return(operators.__dict__[blend_name](self, a, b))


# Required blend -> decided by other code
oper = operators()
blend_name = "add"
a = input("Some input")
b = input("Some other input")
result = oper.calculate(blend_name, a, b)
print(result)

CodePudding user response:

You can create a dictionary that maps the function names to their function objects and use that to call them. For example:

functions = {"add": add, "sub": sub}   # and so on
func = functions[blend_name]
result = func(a, b)

Or, a little more compact, but perhaps less readable:

result = functions[blend_name](a, b)

CodePudding user response:

You could use the globals() dictionary for the module.

result = globals()[blend_name](a, b)

It would be prudent to add some validation for the values of blend_name

  • Related