简体   繁体   English

在 Python 中,“尝试在顶级包之外进行相对导入”错误意味着什么?

[英]What 'Attempted relative import beyond top-level package' error means in Python?

I'm using python 3.7 and ran into a relative import error "Attempted relative import beyond top-level package" with the following folder structure:我正在使用 python 3.7 并遇到一个相对导入错误“尝试在顶级包之外进行相对导入”,文件夹结构如下:

├── app
│   ├── __init__.py
│   ├── services
│   │   └── item_service.py
│   └── views
│       ├── home.py
│       ├── __init__.py

My goal: import variable foo from the top level _init_.py to item_service.py using我的目标:使用从顶层_init_.pyitem_service.py导入变量foo

from .. import foo

Pylint gives the error when trying this.尝试此操作时,Pylint 会出现错误。

However the same exact import statement works in home.py , and if I add a empty _init_.py file to the services folder, the import works.但是,相同的导入语句在home.py有效,如果我将空的_init_.py文件添加到 services 文件夹,则导入有效。

So my my question is, why?所以我的问题是,为什么? Does python require your module to be in a subpackage in order to relatively import parent package's contents?为了相对导入父包的内容,python 是否要求您的模块位于子包中?

For me it got resolved in following ways:对我来说,它通过以下方式得到解决:

  1. First import the directory (import dir)首先导入目录(import dir)
  2. Then try to import the views/class (from dir import views/class)然后尝试导入视图/类(从目录导入视图/类)

To solve: Add init .py to all directories involved.解决方法:将init .py 添加到所有涉及的目录中。

Add sys.path.append("..") BEFORE importing from sibling directory.在从兄弟目录导入之前添加 sys.path.append("..") 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM