“尝试在非包中进行相对导入",尽管在一个目录中包含 __init__.py 的包 [英] 'Attempted relative import in non-package' although packages with __init__.py in one directory

查看:37
本文介绍了“尝试在非包中进行相对导入",尽管在一个目录中包含 __init__.py 的包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 extended.py 的模块,其中包含以下行:

I have a module named extended.py which contains the following line:

from .basic import BasicModule

并且文件 basic.py__init__.py 位于同一目录中.但是,当我尝试将其运行为:

and the file basic.py resides in the same directory as does __init__.py. However, when I try to run it as:

python extended.py

我收到错误:

ValueError: Attempted relative import in non-package

还添加一行:

from __future__ import absolute_import

没有解决问题.也许我太累了,看不到明显的 - 但我没有看到这里的问题.

does not solve the problem. Maybe I am too tired to see the obvious - but I don't see the problem here.

推荐答案

相对导入仅适用于包,但是当您在 extended.py 中导入时,您正在运行一个顶级模块 代替.

Relative imports only work for packages, but when you importing in extended.py you are running a top-level module instead.

当前目录可能包含一个 __init__.py 文件,但这不会使 exended.py 成为包的一部分.

The current directory may hold a __init__.py file but that doesn't make exended.py part of a package yet.

对于被视为包的东西,您需要导入目录名称.以下将起作用:

For something to be considered a package, you need to import the directory name instead. The following would work:

main.py

packagename\
    __init__.py
    basic.py
    extended.py

然后在 main.py 中放入:

import packagename.extended

并且只有 thenextended 包的一部分并执行相对导入工作.

and only then is extended part of a package and do relative imports work.

相对导入现在具有相对的东西,packagename父.

The relative import now has something to be relative to, the packagename parent.

这篇关于“尝试在非包中进行相对导入",尽管在一个目录中包含 __init__.py 的包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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