import a module with a variable
Question: Hello dear programmers Python language. I have a question about importing
modules in another module with Python 2.7.

I want to know how to import a .py module in the form of a variable. In fact,
I would like to import a module based on the needs of my main module to limit
the memory usage of the computer.

For example, suppose I have 25 modules: 1.py, 2.py ... 25.py Suppose my main
module P.y needs, at some point, the modules 2, 7, 15 and 24.py but not the
others. Because, I don't know which modules the main module needs, I currently
import all modules with the import function: import 1 2 3 ... 25 Is there a
python function to import only the modules 2, 7,15 and 24 with a variable ?
(for example: somethink_like_import (variable) where variable contains the
module name to import.)

Thank you.


Answer: Yes!

    
    
    from importlib import import_module
    module = import_module(variable)
    

Example:

    
    
    >>> os = import_module("os")
    >>> os.name
    'nt'
    

