Interactive Python - solutions for relative imports

心不动则不痛 提交于 2020-01-17 04:41:24

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/38488860/interactive-python-solutions-for-relative-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!