如何解决“ValueError:试图在顶级包之外进行相对导入" [英] How to resolve "ValueError: attempted relative import beyond top-level package"

查看:67
本文介绍了如何解决“ValueError:试图在顶级包之外进行相对导入"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目有以下问题,请帮帮我!这是我的包的结构:

I have the following problem with my project, help me please! Here is the structure of my package:

/pkg

/pkg/__init__.py
/pkg/sub1/__init__.py
/pkg/sub2/__init__.py

/pkg/sub1/foo1.py
/pkg/sub2/foo2.py

这是 foo1.py 的实现:

Here is implementation of foo1.py:

from ..sub2 import foo2

def f():
    print("Hello!")

当我运行 foo1 时出现错误:ValueError:试图在顶级包之外进行相对导入.

When I run foo1 I get error: ValueError: attempted relative import beyond top-level package.

我可以通过以下调整来解决它:

I can solve it doing the following adjustment:

import sys
import os
sys.path.append(os.path.abspath(os.path.pardir))

from sub2 import foo2
def f():
    print("Hello!")

但我想知道是否有办法在不导入 sys 并在其中附加父目录的情况下做到这一点.

But I wonder if there is a way to do it without importing sys and appending parent directory in it.

我听说如果我有 .py 文件/pkg/start.py",例如它调用了我的 foo1 模块,那么两个点就可以工作.但是有没有办法直接从foo1调用foo2?

I heard that if I had .py file '/pkg/start.py' for example which called my foo1 module, then two dots would work. However, is there any way to call foo2 from foo1 directly?

推荐答案

在我看来,如果不将 pkg 添加到我的 PATH 中,就不可能从 sub1 中的 sub2 导入模块.原因如下:

It seems to me, that without adding pkg to my PATH it is impossible to import modules from sub2 in sub1. Here is explanation why:

相对导入使用模块的名称 属性来确定该模块在包层次结构中的位置.如果模块的名称不包含任何包信息(例如,它被设置为ma​​in"),那么相对导入将被解析为好像该模块是顶级模块,而不管该模块实际位于何处在文件系统上.

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

这里是python官方网站,其中说明

这篇关于如何解决“ValueError:试图在顶级包之外进行相对导入"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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