1

I have a module like this

# mymodule.py
def myfun():
   print "hello"

being called like this

# main.py
import mymodule

def run(funcname):
    mymodule[funcname]()

in a directory structured like this

./
|
|--mymodule/
   |--__init__.py
   |--mymodule.py
|--main.py

When I call the run method of main.py like this

run("myfun")

I get this error:

TypeError: 'module' object has no attribute '__getitem__'

Understandably. I wouldve been surprised if this worked. The thing is, I need to be able to call a method of a module by string. Is this possible?

1 Answer 1

2

Try this.

def run(funcname):
    getattr(mymodule, funcname)()
Sign up to request clarification or add additional context in comments.

5 Comments

I get this error: AttributeError: 'module' object has no attribute 'myfun'
I assume then that "myfun" is not declared in the module. I've tested the above locally and found it to work.
so iv found that if i import the function like this import mymodule.mymodule.run then i can use this approach. but not otherwise
@dopatraman, i don't think import mymodule.mymodule.run works if run is a function in mymodule, i think you need import mymodule.mymodule as mymodule
hm, i figured as much. what i need to do is dynamically import mymodule

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.