+ 4
Is it possible in Python importing a module by using a fuction or a class?
Is there any possible way like defining a function like: """ def importer(module): return import module """ This does not work because module comes as string. "module" you cannot use like: import "module" Does anyone know how to fix it?
4 Respostas
+ 3
This might be the one you are looking for.
def importer (module ):
__import__(module)
The __import__ function can import modules from variables and strings containing module names
+ 10
You don't be mandatory to import module at very start of your Python code, so yes you can... but:
return import module
... will not work as expected because it doesn't return any value ^^
Anyway, you cannot import a module as a string but you can do:
def import_mod():
import module
def import_mod1():
import module1
def import_mod2()
import module2
import_list = {
'module': import_mod,
'module1': import_mod1,
'module2': import_mod2
}
mod = 'module1'
import_list[mod]()
But anyway, the imported module will be available only within the function scope :(
... And, by the way, it's not 'pythonic':
PEP8 wrote: << Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. >>
source: https://www.python.org/dev/peps/pep-0008/
+ 2
I see... very thanks for your perfectly explained recomment :)
+ 2
Yes! Thank you!