python - How to import a submodule relative to the caller? -
importing module can done in function, passed caller, take simple utility.
def import_reload_or_none(name, reload=true): try: mod = __import__(name) if reload: import importlib mod = importlib.reload(mod) return mod except exception: import traceback traceback.print_exc() return none
this works root-level modules, i'm not sure how done when function in module or when relative imports used.
how function made work replace eg:
from . import my_package_module
try passing path module want import function example:
def import_reload_or_none(name, reload=true, path=none): mod = __import__(path + '/' + name) if path not none else __import__(name) if reload: import importlib mod = importlib.reload(mod) return mod
then, if want import relative path can use
import_reload_or_none(my_package_module, path = '.')
Comments
Post a Comment