Calling a Function of a Module by Using Its Name (A String)

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 function from a stored string in Python

You can do this :

eval(input("What function do you want to call? ") + '()')

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

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
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))


or if it's a function:

def install():
print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)

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)

How can I call a function by its name inside the class

As already indicated in the comments to the original question, you need to access the methods on the instance. For instance:

class A:
def C(self, person):
getattr(self, person)()
except AttributeError:
print(f'there is no method for `{person}` in the A class')

def John(self):
print("I am john")

def Ben(self):
print("I am Ben")

I am john

there is no method for `Daniel` in the A class

Although it is legit to wonder why you would want to implement such a programming pattern, getattr is there exactly for similar purposes. Still, I agree with the comments that without a better explanation, this is a programming pattern one should avoid.

python string to a function call with arguments, without using eval

You might want to take a look at the ast Python module, which stands for abstract syntax trees. It's mainly used when you need to process the grammar of the programming language, work with code in string format, and so much more functions available in the official documentation.

  • In this case eval() function looks like the best solution, clear and readable, but safe only under certain conditions. For example, if you try to evaluate a code that contains a class not implemented in the code, it will throw an exception. That's the main reason why eval is sometimes unsafe.

How is calling module and function by string handled in python?

Use the __import__(....) function:

(David almost had it, but I think his example is more appropriate for what to do if you want to redefine the normal import process - to e.g. load from a zip file)

Call method by annotation

you could do something like this:

class Test:

def method(self,name):
return getattr(self,f"__method_{name}")()

def __method_a():...
def __method_b():...

find and call any function by function in string

Though possible, in Python, few times one will need to pass a function by its name as a string. Specially, if the wanted result is for the function to be called in its destination - the reason for that is that functions are themselves "first class objects" in Python, and can be assigned to new variable names (which will simply reference the function) and be passed as arguments to other functions.

So, if one wants to pass sin from the module math to be used as a numericd function inside some other code, instead of general_function_testing('sin', 'math', ...) one can simply write:

import math
general_function_testing(math.sin, ...)

And the function callad with this parameter can simply use whatever name it has for the parameter to call the passed function:

def general_function_testing(target_func, ...):
result = target_func(argument)

While it is possible to retrieve a function from its name and module name as strings, its much more cumbersome due to nested packages: the code retrieveing the function would have to take care of any "."s in the "function path" as you call it, make carefull use of the built-in __import__, which allows one to import a module given its name as a string, though it has a weird API, and then retrieve the function from the module using a getattr call. And all this to have the a reference to the function object itself, which could be passed as a parameter from the very first moment.

The example above doing it via strings could be:

import sys
def general_function_testing(func_name, func_path, ...):
__import__(func_path) # imports the module where the function lives, func_path being a string
module = sys.modules[func_path] # retrieves the module path itself
target_func = getattr(module, func_name)
result = target_func(argument)

Related Topics

Leave a reply