交互式Python-相对导入的解决方案 [英] Interactive Python - solutions for relative imports

查看:129
本文介绍了交互式Python-相对导入的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自十亿分之一秒的Python相对进口量:

  • 要使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.moduleXsubpackage2.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 the import 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆