Question: I'm just starting out in python after years of Java, C, c++, etc.
I have a long list of files/modules that each contain one major method that I want to call dynamically. For each keyword, I have a .py file with the name get\_foo and inside each get\_foo.py, there is a foo method. So I want to pass in the command name "foo" and execute the method get\_foo.foo()

I really don't want to do this with an ugly if/then/else block

```
sections = [ "abstract",  "claim",  "drawing", "examiner"]
command = "claim"

```

What I want to something like

```
exec("get_" + command + "." + command)

```

But I really don't know even which areas of exec/eval/etc do this.

Answer: 
Use the [`importlib` module](http://docs.python.org/2/library/importlib.html) to dynamically import, and `getattr()` to find your function:

```
import importlib

def call_command(cmd):
    mod = importlib.import_module('get_' + cmd)
    func = getattr(mod, cmd)
    return func()

```

Or, simply import all your modules and add them to a dict to map command to callable:

```
import get_foo, get_bar, get_baz

commands = dict(foo=get_foo.foo, bar=get_bar.bar, baz=get_baz.baz)

def call_command(cmd):
    return commands[cmd]()

```
You can have a function which calls a function from a module:

```
def call_function(func):
    module = __import__("get_" + func)
    return getattr(module, func)()

```

Then call this function like this:

```
call_function("claim")

```