Andrew Hryvachevskyi
Andrew Hryvachevskyi

Reputation: 115

How on python to change the name of the launched instruction using the input parameter of the function?

How on python to change the name of the launched instruction using the input parameter of the function? How to do this without using if and else? The idea is to make a statement something like .format() for strings. See an example of an idea below.

def run_module(file, module_name):
    .
    .
    .
    res = object.module_name(file, param2, param3, ...)
    .
    .
    .
    return

object - an entity from the library, there is no possibility to change. I would be grateful for any constructive advice.

Upvotes: 0

Views: 37

Answers (2)

a.deshpande012
a.deshpande012

Reputation: 744

Similar to what Cibin said, you're using module_name as the name of a function, but the name of the parameter makes it seem as if it's the name of a module instead.

Assuming module_name refers to the name of a function to invoke, an alternative to the exec() is using getattr(), which is probably a bit cheaper/faster.

For example:

def run_module(file, module_name):
    .
    .
    .
    res = getattr(object, module_name)(file, param2, param3, ...)
    .
    .
    .
    return

The getattr() method returns the function module_name of the object object, and then you can invoke that returned function like any normal function, and pass in the required parameters.

Upvotes: 1

Cibin Joseph
Cibin Joseph

Reputation: 1273

Firstly, are you sure module_name is a module and not a function?

You could make it a string and then execute that like this:

def run_module(file, module_name):
    .
    .
    commandString = "res = object." + module_name + "(file, param2, param3, ...)"
    exec(commandString)
    .
    .
    return

This might be a related question you'd like to look into:
1. How do I execute a string containing Python code in Python?

Upvotes: 0

Related Questions