如何修复“在非包中尝试相对导入"即使使用 __init__.py [英] How to fix "Attempted relative import in non-package" even with __init__.py

查看:22
本文介绍了如何修复“在非包中尝试相对导入"即使使用 __init__.py的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循 PEP 328,使用以下目录结构:

I'm trying to follow PEP 328, with the following directory structure:

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py
    __init__.py

core_test.py 我有以下导入语句

In core_test.py I have the following import statement

from ..components.core import GameLoopEvents

但是,当我运行时,出现以下错误:

However, when I run, I get the following error:

tests$ python core_test.py 
Traceback (most recent call last):
  File "core_test.py", line 3, in <module>
    from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package

搜索我发现相对路径即使使用 __init__ 也不起作用.py" 和 "从亲属导入模块路径",但他们没有帮助.

Searching around I found "relative path not working even with __init__.py" and "Import a module from a relative path" but they didn't help.

这里有什么我遗漏的吗?

Is there anything I'm missing here?

推荐答案

是的.您没有将其用作包.

Yes. You're not using it as a package.

python -m pkg.tests.core_test

这篇关于如何修复“在非包中尝试相对导入"即使使用 __init__.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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