交互式Python-相对导入的解决方案 [英] Interactive Python - solutions for relative imports
问题描述
- 要使
from .. import
起作用,模块的名称必须至少具有与import
语句中相同的点. - ...如果以交互方式运行解释器,则该交互式会话的名称为
__main__
- 因此,您不能直接从交互式会话进行相对导入
我喜欢在编写生产代码之前使用交互式Jupyter Notebook会话来探索数据和测试模块.为了使团队成员清楚易懂,我希望将笔记本放在我正在测试的程序包和模块旁边的interactive
程序包中.
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleY.py
moduleZ.py
subpackage2/
__init__.py
moduleZ.py
interactive/
__init__.py
my_notebook.ipynb
在interactive.my_notebook.ipynb
中的交互式会话期间,您将如何导入其他模块,例如subpackage1.moduleX
和subpackage2.moduleZ
?
我当前使用的解决方案是将父包附加到sys.path
.
import sys
sys.path.append("/Users/.../package/")
import subpackage1.moduleX
import subpackage2.moduleZ
From Python relative imports for the billionth time:
- For a
from .. import
to work, the module's name must have at least as many dots as there are in theimport
statement. - ... if you run the interpreter interactively ... the name of that interactive session is
__main__
- Thus you cannot do relative imports directly from an interactive session
I like to use interactive Jupyter Notebook sessions to explore data and test modules before writing production code. To make things clear and accessible to teammates, I like to place the notebooks in an interactive
package located alongside the packages and modules I am testing.
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleY.py
moduleZ.py
subpackage2/
__init__.py
moduleZ.py
interactive/
__init__.py
my_notebook.ipynb
During an interactive session in interactive.my_notebook.ipynb
, how would you import other modules like subpackage1.moduleX
and subpackage2.moduleZ
?
The solution I currently use is to append the parent package to sys.path
.
import sys
sys.path.append("/Users/.../package/")
import subpackage1.moduleX
import subpackage2.moduleZ
这篇关于交互式Python-相对导入的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!