Python: Call a Function from String Name

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.

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.

Execute function based on function's name string

You may use locals() (or globals()) to fetch the reference of function based on string. Below is the sample example:

# Sample function
def foo(a, b):
print('{} - {}'.format(a, b))

# Your string with functions name and attributes
my_str = "foo x y"

func, *params = my_str.split()
# ^ ^ tuple of params string
# ^ function name string

Now, pass the function string as a key to the locals() dict with *params as argument to the function as:

>>> locals()[func](*params)
x - y # output printed by `foo` function

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 can i call function with string value that equals to function name

Yes, you can call it with eval like this:

a = "myFunc()" 

def myFunc():
print("Bla bla")

eval(a)
Bla bla

Does this help? Thanks! Eval is useful for calling functions in a list for example, you can iterate a list of functions like:

for item in functionlist:
eval(item)

Calling a function from other python file of whose name is stored in a string variable (dictionary)

Use getattr() instead.

others = {0 : 'num_0', 1 : 'num_1', 2 : 'num_2', 3 : 'num_3', 4 : 'num_4', 5 : 'num_5', 6 : 'num_6', 7 : 'num_7', 8 : 'num_8', 9 : 'num_9'}

#custom_string = 'a0b1c2' #Example

for i in custom_string:
if i.isnumeric():
getattr(letterMatrix, others[i])(self.font_size, self.character, row)

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



Leave a reply



Submit