charlie Pearson
charlie Pearson

Reputation: 13

How to run a function named in a variable?

I want to run a function and the name of that function is the value of a variable. So if the variable == "Hello" it would run the function Hello(). the variable is from a certain cell in an excel document (I just thought I would add that).

I have tried using eval() but that seems to not work when the function is more then just output of text.

this = sheet["B"+str(row)].value 
eval(function+"()")

I want it just to run the function but the shell just skips right over - eval(this+"()") - so I am not sure what is actually happening.

Upvotes: 0

Views: 80

Answers (3)

Dave
Dave

Reputation: 622

return the function by name using the locals variable, check for it, verify it is actually callable then run it.

def test_func():
    print("In test function")

func_name = "test_func"

if func_name in locals() and callable(locals()[func_name]):
    locals()[func_name]()

output

In test function

As mentioned by Thomas, this can also be done using global() rather than locals() if the function is in the global name space. In addition if you would like to check for a method in a class, and call that instead you'll need to use the hasattr() function.

Upvotes: 0

Thomas
Thomas

Reputation: 181815

The globals() function returns a dictionary representing the current scope, so globals()[this] gives a reference to the function, and globals()[this]() will call it with no arguments.

This is a bit safer than eval because it won't execute arbitrary code (although still risky on untrusted input).

Upvotes: 1

Manu mathew
Manu mathew

Reputation: 989

You could run the function using eval() as:

eval(variable)()

Upvotes: 2

Related Questions