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.
Call a Python method by name
Use the built-in getattr()
function:
class Foo:
def bar1(self):
print(1)
def bar2(self):
print(2)
def call_method(o, name):
return getattr(o, name)()
f = Foo()
call_method(f, "bar1") # prints 1
You can also use setattr()
for setting class attributes by names.
How to get the caller's method name in the called method?
inspect.getframeinfo and other related functions in inspect
can help:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print('caller name:', calframe[1][3])
...
>>> f1()
caller name: f1
this introspection is intended to help debugging and development; it's not advisable to rely on it for production-functionality purposes.
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? ") + '()')
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
.
How to call a method whose name is stored in a variable
Create a dict of functions that you want to call using a string:
def test(test_config):
for i in test_config:
print i.header //prints func1
print type(i.header)
try:
methods[i.header]()
except (AttributeError, TypeError):
logging.error("Method %s not implemented"%(i.header))
def func1():
print "In func1"
def func2():
print "In func2"
methods = {u'func1':func1, u'func2':func2} #Methods that you want to call
Using class:
class A:
def test(self, test_config):
try:
getattr(self, i.header)()
except AttributeError:
logging.error("Method %s not implemented"%(i.header))
def func1(self):
print "In func1"
x = A()
x.test(pass_something_here)
How to call Python functions dynamically
If don't want to use globals, vars
and don't want make a separate module and/or class to encapsulate functions you want to call dynamically, you can call them as the attributes of the current module:
import sys
...
getattr(sys.modules[__name__], "clean_%s" % fieldname)()
Determine function name from within that function (without using traceback)
Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar"
or bar.__name__
depending on context.
The given rejection notice is:
This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.
Using a string in function name during call in python
Create a dict of your functions and use it to dispatch using somevar
:
class MyClass:
def a1_suffix(self, option):
return "does something"
def a2_suffix(self, option):
return "does something else"
def myfunction(self, somevar, option):
functions = {"a1": self.a1_suffix, "a2": self.a2_suffix}
func = functions[somevar]
return func(option)
Related Topics
A Mutable Type Inside an Immutable Container
Python Giving Filenotfounderror for File Name Returned by Os.Listdir
Expand Python Search Path to Other Source
Is There a Python Equivalent of the C# Null-Coalescing Operator
Django HTML Template Can't Find Static CSS and Js Files
Installation Issue with Matplotlib Python
Splitting a String into Words and Punctuation
How to Capture Multiple Camera Streams with Opencv
Python - Classes and Oop Basics
Translate Every Element in Numpy Array According to Key
How to Operate on a Dataframe with a Series for Every Column
Creating a List of Dictionaries Results in a List of Copies of the Same Dictionary
Python 32-Bit Memory Limits on 64Bit Windows
Performing a Getattr() Style Lookup in a Django Template
Does Reading an Entire File Leave the File Handle Open