Reputation: 35
I'm trying to make a code where a user inputs a function and I check if the function exists or not. So I think I should find a way for them to call the function and if I get a Parameter --- not filled or no error it works. If I get a --- not defined I can say It doesn't exist. How do I make their string into a callable function?
Upvotes: 0
Views: 40
Reputation: 2269
Here is a demo code which calls the function inputted by the user. Please implement your own checks (if statements)
Example code:
def demo():
print("Hello from demo()")
# input from user
text = input()
# check here if the function exists
# this is how you can make user string into a callable function
globals()[text]()
Upvotes: 1
Reputation: 83
You can define the methods inside a class and use hasattr() in your code to determine if the method exists or not.
class Person:
def fun():
print("a random function")
person = Person()
print(hasattr(person, 'fun'))
print(hasattr(person, 'random'))
output
True
False
Upvotes: 0