相对进口的python包装 [英] python packaging for relative imports

查看:41
本文介绍了相对进口的python包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先:对不起,我知道有很多关于相对导入的问题,但我只是没有找到解决方案.如果可能,我想使用以下目录布局:

First off all: I'm sorry, I know there has been lots of question about relative imports, but I just didn't find a solution. If possible I would like to use the following directory layout:

myClass/
    __init__.py
    test/
        demo.py
        benchmark.py
        specs.py
    src/
        __init__.py
        myClass.py

现在我的问题是:

  • 包中的测试文件如何正确导入 myClass.py?

  • How do the test files from within the package properly import myClass.py?

假设您将 myClass 作为 libs/myClass 或 include/myClass 中的子模块,您将如何从外部导入包?

How would you import the package from outside, assuming you take myClass as submodule in libs/myClass or include/myClass?

到目前为止,我找不到一个优雅的解决方案.据我了解 Guido 的决定 应该是可能的做 from ..src import myClass 但这会出错:

So far I couldn't find an elegant solution for this. From what I understand Guido's Decision it should be possible to do from ..src import myClass but this will error:

ValueError: 在非包中尝试相对导入

它看起来没有将 myClass 视为包.阅读文档:

Which looks as it doesn't treat myClass as packages. Reading the docs:

需要 __init__.py 文件才能使 Python 将目录视为包含包;

The __init__.py files are required to make Python treat the directories as containing packages;

似乎我遗漏了一些指定包脚本在哪里的东西,我应该使用 .pth 吗?

It seems I'm missing something that specifies where the scripts of the package are, should I use .pth ?

推荐答案

ValueError: 在非包中尝试相对导入

意味着您尝试在不是包的模块中使用相对导入.它的问题在于包含此 from ... import 语句的文件,而不是您尝试导入的文件.

Means you attempt to use relative import in the module which is not package. Its problem with the file which has this from ... import statement, and not the file which you are trying to import.

因此,例如,如果您在测试中进行相对导入,则应将测试作为包的一部分.这意味着

So if you are doing relative imports in your tests, for example, you should make your tests to be part of your package. This means

  1. __init__.py 添加到 test/
  2. 从一些外部脚本运行它们,比如鼻子测试

如果你以 python myClass/test/demo.py 的形式运行某些东西,相对导入也将不起作用,因为你运行的是演示模块而不是包.相对导入要求使用它们的模块本身作为包模块导入,from myClass.test.demo import blabla,或相对导入.

If you run something as python myClass/test/demo.py, relative imports will not work too since you are running demo module not as package. Relative imports require that the module which uses them is being imported itself either as package module, from myClass.test.demo import blabla, or with relative import.

这篇关于相对进口的python包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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