I am trying to write a generic module that provides functions that act as a wrapper to specific implementation. Example, my main.py script will call profile.py functions profile()
. The profile.py will then call either machineA or machineB measure()
function depending on the cmd line arg which i pass in.
/main.py
tools/profile.py -- # provides function profile
machineA/measure.py # provides function measure
machineB/measure.py # provides function measure
Currently my tools/profile.py does this
if machine == 'machineA':
from machineA import measure
else:
from machineB import measure
def profile():
return measure.measure()
I am using modules to do this functionality, I think there maybe a way to do this with classes, however i am not too familiar with classes to know how to get started. Any tips would be appreciated.
The simple (though hacky) way is to use __import__
directly.
measure = __import__(machine).measure
Slightly cleaner would be to use the importlib
module.
import importlib
measure = importlib.import_module(machine).measure
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.