为什么同样的代码在一个文件中导入一个函数,而在另一个文件中导入同名的模块?

问题描述 投票:0回答:1

同样的导入语句 from mypackage._aux import is_error 在类似的文件中,有两种不同的含义。

第一个是预期行为,因为 _aux/__init__.py 包含 from .is_error._is_error import is_error. (格式 from .folder.file import function)

当我运行 pytest,这两个测试在 _abbrev_testing_test.py 失败,因为 is_error 不是预期的功能。(TypeError: 'module' object is not callable)

当我使用我想用新函数缩写的行时,它就会工作。enter image description here这包括测试中的 _foobar_test.py - 那么 _foobar.py功能 是进口的。

但在 _abbrev_testing.py模块 被导入。enter image description here

有谁明白这两个文件的区别吗?我是否应该换一种方式来做?

我很想知道是否有什么逻辑规则可以避免这种情况。(对我来说,这只是看起来很荒谬和不稳定。)

编辑。 在两个文件中,当我使用一个长的导入语句,而不是依赖... ... _aux/__init__.py:

  • (格式:短。from mypackage._aux import is_error (格式 from _aux import function)

  • 长。from mypackage._aux.is_error._is_error import is_error (格式 from _aux.folder.file import function)

这个问题可以概括为: 什么是 _abbrev_testing.py 破坏 __init__.py

编辑2 重现的步骤:

me@ubuntu:~$ git clone https://github.com/watchduck/module_object_is_not_callable.git
me@ubuntu:~$ cd module_object_is_not_callable/
me@ubuntu:~/module_object_is_not_callable$ virtualenv -p python3 env

用IDE打开项目。

(env) me@ubuntu:~/module_object_is_not_callable$ pip install pytest
(env) me@ubuntu:~/module_object_is_not_callable$ pytest
pytest python-import python-packaging relative-import
1个回答
0
投票

在 _abbrev_testing.py 中,什么破坏了 启动.py?

明白了--如果你把:

from .is_error._is_error import is_error
from .abbrev_testing._abbrev_testing import abbrev_testing
from .foobar._foobar import foobar

你的init问题就会消失 你是。

from .abbrev_testing._abbrev_testing import abbrev_testing
from .is_error._is_error import is_error

将is_error设置为 功能 "is_error "仅指 之后 你导入了 .abbrev_testing._abbrev_testing - 其中 is_error 已经(正确地)作为一个模块导入。

我应该用不同的方式来做吗?

当然可以。不要把函数命名为与模块包相同的名字。它们是不同的东西,所以应该有不同的名字。另外--避免使用类似的重复名称,以及前导下划线。使代码很难阅读 (所以我多次打开 _abbrev_testing_errors.py,因为它看起来和 _abbrev_testing.py 或 _abbrev_testing_test.py 非常相似) - 为测试保留 "test".我是认真的 - python 的导入系统很复杂,但复杂是应该的,因为这是一个复杂的问题。正确的命名使这种复杂性变得可控。

© www.soinside.com 2019 - 2024. All rights reserved.