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]()

```
solution 1 

```
from get_foo1 import foo1 # get_foo1.py in directory
from get_foo2 import foo2 # get_foo2.py in directory
foo1()
foo2()

```

can be done in other ways too

```
import get_foo1
import get_foo2

get_foo1.foo1()
get_foo2_foo2()

```

to dinamically call them you have a lot of ways too

```
commands = {"foo1":foo1, "foo2":foo2} 
# notice foo1 and foo2 have no "()" because we're referencing function and not calling it

#and then call them

commands["foo1"]()   # notice (), this means we're calling function now

```