I have a string whose content is a function name, how to refer to the corresponding function in Python?
Since you are taking user input, the safest way is to define exactly what is valid input:
dispatcher={'add':add}
w='add'
try:
function=dispatcher[w]
except KeyError:
raise ValueError('invalid input')
If you want to evaluate strings like 'add(3,4)'
, you could use safe eval:
eval('add(3,4)',{'__builtins__':None},dispatcher)
eval
in general could be dangerous when applied to user input. The above is safer since __builtins__
is disabled and locals
is restricted to dispatcher
. Someone cleverer than I might be able to still cause trouble, but I couldn't tell you how to do it.
WARNING: Even eval(..., {'__builtins__':None}, dispatcher)
is unsafe to be applied to user input. A malicious user could run arbitrary functions on your machine if given the opportunity to have his string evaluated by eval
.
Calling a function of a module by using its name (a string)
Given a module foo
with method bar
:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr
can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
Convert string into a function call
Sure, you can use globals
:
func_to_run = globals()[ran_test_opt]
func_to_run()
Or, if it is in a different module, you can use getattr
:
func_to_run = getattr(other_module, ran_test_opt)
func_to_run()
Python: call a function from string name
If it's in a class, you can use getattr:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
method()
or if it's a function:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
Call a function from a stored string in Python
You can do this :
eval(input("What function do you want to call? ") + '()')
How to pass functions with arguments as parameter to another function in python with function name as a string?
Replace eval(function_name)(img,parameter)
with:
globals()[function_name](img,parameter)
Note that your desired function should be in the same module in my answer, if it is not, read this link or This about globals
and locals
in python to find the best thing for your problem.
Also, you can access a function of another module with getattr
, like this:
getattr(module, func)(*args, **kwargs)
Related Topics
Python: Urllib2 How to Send Cookie with Urlopen Request
Why Should I Close Files in Python
How to Print the Key-Value Pairs of a Dictionary in Python
Is Tensorflow Compatible with a Windows Workflow
How to Make a Python Script Executable
Is the += Operator Thread-Safe in Python
Pandas Reading CSV as String Type
Matplotlib Dateformatter for Axis Label Not Working
Selenium Webdriver: How to Download a PDF File with Python
How to Use Multiple Requests and Pass Items in Between Them in Scrapy Python
Changing Order of Unit Tests in Python
Running a Tkinter Form in a Separate Thread
Sending Mail from Python Using Smtp
[] and {} VS List() and Dict(), Which Is Better
Pandas: Convert Dtype 'Object' to Int
How to Draw Axis in the Middle of the Figure