英文:
Conditionally modify import statements
问题
I have a collection of .py files in the following file structure:
packagename
mod_1.py
mod_2.py
script_1.py
etc.
These files do two things:
-
They're bundled into an application (a JMP/JSL add-in, although not relevant here). In this application
script_1.py
is called, and it contains import statements likeimport mod_1
.mod_1.py
in turn importsmod_2.py
asimport mod_2
. This is fine. -
The files are also bundled up into a python package called
packagename
. In this context when I want to importmod_2.py
insidemod_1.py
I callimport packagename.mod_2
. This is also fine.
I presently implement this in mod_1.py
, very painfully, as:
if 'addin' in file:
import mod_2
else:
import packagename.mod_2
This works but I've got lots and lots of modules (more than just mod_1, mod_2). Is there a way to do something like this (pseudocode)?:
if 'addin' in file:
import_prefix = ''
else:
import_prefix = 'packagename.'
import import_prefix + mod_2
This answer seems to cover half of what I'm looking for, but not everything:
https://stackoverflow.com/questions/12229580/python-importing-a-sub-package-or-sub-module
英文:
I have a collection of .py files in the following file structure:
packagename\
mod_1.py
mod_2.py
script_1.py
etc.
These files do two things:
- They're bundled into an application (a JMP/JSL add-in, although not relevant here). In this application
script_1.py
is called, and it contains import statements likeimport mod_1
.mod_1.py
in turn importsmod_2.py
asimport mod_2
. This is fine. - The files are also bundled up into a python package called
packagename
. In this context when I want to importmod_2.py
insidemod_1.py
I callimport packagename.mod_2
. This is also fine.
I presently implement this in mod_1.py
, very painfully, as:
if 'addin' in __file__:
import mod_2
else:
import packagename.mod_2
This works but I've got lots and lots of modules (more than just mod_1, mod_2). Is there a way to do something like this (pseudocode)?:
if 'addin' in __file__:
import_prefix = ''
else:
import_prefix = 'packagename.'
import import_prefix + mod_2
This answer seems to cover half of what I'm looking for, but not everything:
https://stackoverflow.com/questions/12229580/python-importing-a-sub-package-or-sub-module
答案1
得分: 1
你可能只想使用importlib.import_module
。
import importlib
def _import(module_name: str):
if 'addin' in __file__:
return importlib.import_module(module_name)
return importlib.import_module(f'packagename.{module_name}')
mod_2 = _import(mod_2)
英文:
You may just want to use importlib.import_module
.
import importlib
def _import(module_name: str):
if 'addin' in __file__:
return importlib.import_module(module_name)
return importlib.import_module(f'packagename.{module_name}')
mod_2 = _import(mod_2)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论