I am trying to build a software package that fixes arbitrary data inconsistencies in one of my databases. My design includes two classes - Problem
and Fix
.
The problems are SQL queries stored as .cfg
files (e.g. problem_001.cfg
), and the fixers are stored as Python files (e.g. fix_001.py
). The query config file has a reference to the Python file name. Each fixer has a single class Fix
, which inherits from a base class BaseFix
.
`-- problems
|-- problem_100.cfg
|-- problem_200.cfg
|-- problem_300.cfg
`-- ...
`-- fixer
|-- __init__.py
| |-- fixers
| | |-- fix_100.py
| | |-- fix_200.py
| | |-- fix_300.py
| | |-- ...
| `-- ...
`-- ...
I would like to 开发者_Python百科instantiate Problem
files and supply them with Fix
objects in a clean way. Is there a way to do it without keepping all the fixers in the same file?
UPDATE:
This is the final code that worked (thanks, @Space_C0wb0y):
fixer_name='fix_100'
self.fixer=__import__('fixer.fixers', globals(), locals(),
[fixer_name]).__dict__[fixer_name].Fix()
You can dynamically import modules using the builtin __import__
, which takes the module-name as string-argument (see here). The modules do have to be in the module search path.
精彩评论