Skip to content
Advertisement

Call Python function using dynamic string variables

I am trying to create a dynamic method executor, where I have a list that will always contain two elements. The first element is the name of the file, the second element is the name of the method to execute.

How can I achieve this?

My below code unfortunately doesn’t work, but it will give you an good indication of what I am trying to achieve.

from logic.intents import CenterCapacity

def method_executor(event):
    call_reference = ['CenterCapacity', 'get_capacity']

    # process method call
    return call_reference[0].call_reference[1]

Thanks!

Advertisement

Answer

You can use __import__ to look up the module by name and then then use getattr to find the method. For example if the following code is in a file called exec.py then

def dummy(): print("dummy")

def lookup(mod, func):
    module = __import__(mod)
    return getattr(module, func)

if __name__ == "__main__":
    lookup("exec","dummy")()

will output

dummy

Addendum

Alternatively importlib.import_module can be used, which although a bit more verbose, may be easier to use.

The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg.mod), while __import__() returns the top-level package or module (e.g. pkg).

def lookup(mod, func):
    import importlib
    module = importlib.import_module(mod)
    return getattr(module, func)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement