1

I want to determine whether the input string is a valid function name or not. Is there any way to substitute the value of the variable before being passed to isfunction call ?

#!/usr/bin/python
def testFunc():
    print "Hello world!";
    return;

myString = "testFunc";
isfunction(testFunc); // This returns **True**
isfunction(myString); // This returns **False**
Ashwin
  • 993
  • 1
  • 16
  • 41

2 Answers2

1

One way of doing that is using eval, which interprets string as code:

try:
    eval(myString)
except NameError:
    # not a function
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • This would execute any code that the string contains, and could cause far more errors than NameError can capture. – Rob Foley Sep 03 '15 at 13:24
1

Assuming you want to check to see if there exists a loaded function with You could try this:

try:
    if hasattr(myString, '__call__'):
        func = myString
    elif myString in dir(__builtins__):
        func = eval(myString)
    else:
        func = globals()[myString]

except KeyError:
    #this is the fail condition

# you can use func()

The first if is actually unnecessary if you will always guarantee that myString is actually a string and not a function object, I just added it to be safe.

In any case, if you actually plan on executing these functions, I'd tread carefully. Executing arbitrary functions can be risky business.

EDIT:

I added another line to be a bit more sure we don't actually execute code unless we want to. Also changed it so that it is a bit neater

Rob Foley
  • 601
  • 4
  • 6