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**
4
  • 2
    Do you mean that the string is a valid function name, or the variable is a function? Commented Sep 3, 2015 at 13:06
  • @khelwood: I want to know the value present inside myString is valid or not Commented Sep 3, 2015 at 13:09
  • Possible duplicate: stackoverflow.com/questions/624926/… Commented Sep 3, 2015 at 13:28
  • 1
    @Ashwin Then why should isfunction(myString) return false when myString is "testFunc"? Commented Sep 3, 2015 at 14:08

2 Answers 2

1

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

try:
    eval(myString)
except NameError:
    # not a function
Sign up to request clarification or add additional context in comments.

1 Comment

This would execute any code that the string contains, and could cause far more errors than NameError can capture.
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

2 Comments

hasattr returns False because it considers myString as String variable
You are correct. Which is why the other conditions exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.