+ 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?

8th Jul 2017, 10:29 PM
YĂŒsein Ali
YĂŒsein Ali - avatar
4 Answers
+ 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
11th Jul 2017, 2:50 PM
Ms Arnold
Ms Arnold - avatar
+ 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/
8th Jul 2017, 10:56 PM
visph
visph - avatar
+ 2
I see... very thanks for your perfectly explained recomment :)
8th Jul 2017, 11:00 PM
YĂŒsein Ali
YĂŒsein Ali - avatar
+ 2
Yes! Thank you!
11th Jul 2017, 2:51 PM
YĂŒsein Ali
YĂŒsein Ali - avatar