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.


Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:

# Get class from globals and create an instance
m = globals()['our_class']()

# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')

# Call it
func()

For example:

class A:
    def __init__(self):
        pass

    def sampleFunc(self, arg):
        print('you called sampleFunc({})'.format(arg))

m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')

# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')

And, if not a class:

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

globals()['sampleFunc']('sample arg')

Based on Patrick's solution, to get the module dynamically as well, import it using:

module = __import__('foo')
func = getattr(module, 'bar')
func()

  • Using locals(), which returns a dictionary with the current local symbol table:

    locals()["myfunction"]()
    
  • Using globals(), which returns a dictionary with the global symbol table:

    globals()["myfunction"]()
    

Tags:

Python

Object