Reputation: 28
My_Module=input()
My_Method=input()
from My_Module import My_Method
I'm writing a program and I need to import a method first.
But when I type what I did in above it sends an error and says can't "import name My_Method from My_Module
".
I tried 2 other different codes but they didn't work either.I know that My_Method
is a name and can't be imported but what can I do to solve this problem and have it worked?
Upvotes: 0
Views: 24
Reputation: 10403
You need to use __import__
to get the module in a dynamic way (using a variable content as name)
Then, you need to use getattr
to get the function within the module.
import importlib
modulename = input('module ')
funcname = input('func ')
mod = importlib.import_module(modulename)
func = getattr(mod, funcname)
print(func)
# call the function
func()
Thx to Patrick Haugh and his comment
Upvotes: 2