同样的导入语句 from mypackage._aux import is_error
在类似的文件中,有两种不同的含义。
In _aux/foobar/_foobar.py
它导入的函数 is_error
从 _aux/is_error/_is_error.py
.
但在 _aux/abbrev_testing/_abbrev_testing.py
它导入整个模块 _aux/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
)
当我使用我想用新函数缩写的行时,它就会工作。这包括测试中的 _foobar_test.py
- 那么 _foobar.py
的 功能 是进口的。
但在 _abbrev_testing.py
的 模块 被导入。
有谁明白这两个文件的区别吗?我是否应该换一种方式来做?
我很想知道是否有什么逻辑规则可以避免这种情况。(对我来说,这只是看起来很荒谬和不稳定。)
编辑。 在两个文件中,当我使用一个长的导入语句,而不是依赖... ... _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
在 _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 的导入系统很复杂,但复杂是应该的,因为这是一个复杂的问题。正确的命名使这种复杂性变得可控。