__import__
Such scenes are often seen in projects , According to environment variable , Load different configurations .
Test environment :config_dev.py
db_host = '127.0.0.1'
Formal environment :config_pro.py
db_host = '192.168.0.1'
This is the case __import__
To dynamically load , Simple examples such as :
project_env = 'dev'
if project_env == 'dev':
config = __import__("config_dev")
else:
config = __import__("config_pro")
print(config.db_host)
# result :
# 127.0.0.1
fromlist
__import__
There are a lot of parameters , among name
Is a must , Among other parameters fromlist
Is an important parameter . In the previous example , The two configuration and import module files are in the same folder , That's not there ? Now? , Change project results :
├── conf
│ ├── __init__.py
│ ├── config_dev.py
│ └── config_pro.py
└── demo.py
Change it demo.py
Code for :
project_env = 'dev'
if project_env == 'dev':
config = __import__("conf.config_dev")
else:
config = __import__("conf.config_pro")
print(config)
Output results :
<module 'conf' from 'D:\\project\\python\\black_api\\demo\\conf\\__init__.py'>
See that ? Our intention is to import different modules ,config_dev
or config_pro
, But the actual import is conf
modular , Not in line with our expectations . In this case , Need to use fromlist
Parameters :
project_env = 'pro'
if project_env == 'dev':
config = __import__("conf.config_dev", fromlist="config_dev")
else:
config = __import__("conf.config_pro", fromlist="config_pro")
print(config)
Output results :
<module 'conf.config_pro' from 'D:\\project\\python\\black_api\\demo\\conf\\config_pro.py'>
Conclusion : In the use of __import__
Function time ,name
If the address of contains the name of the package , Be sure to use fromlist
Parameter to indicate which module in the package to import , Otherwise, the entire package will be imported .
importlib.import_module
importlib
Modular import_module
Method compared to __import__
More friendly , More convenient to use . Let's take an example 2 Project structure , modify demo.py
Code for :
import importlib
project_env = 'dev'
if project_env == 'dev':
# Absolutely import
config = importlib.import_module('conf.config_dev')
else:
# Relative Import
config = importlib.import_module('.config_pro', package='conf')
print(config.db_host)
When using relative Import , Be sure to name
Add a dot in front