具有相同名称的Python模块(即,重复使用软件包中的标准模块名称) [英] Python modules with identical names (i.e., reusing standard module names in packages)
问题描述
假设我有一个包含模块的软件包:
Suppose I have a package that contains modules:
SWS/
__init.py__
foo.py
bar.py
time.py
,并且这些模块需要引用彼此包含的功能.似乎我的time.py
模块遇到了问题,因为有一个同名的标准模块.
and the modules need to refer to functions contained in one another. It seems like I run into problems with my time.py
module since there is a standard module that goes by the same name.
例如,在我的foo.py
模块同时需要我的SWS.time
和标准python time
模块的情况下,我遇到了麻烦,因为解释器将在程序包内部查找并找到我的time.py
模块它遇到了标准的time
模块.
For instance, in the case that my foo.py
module requires both my SWS.time
and the standard python time
modules, I run into trouble since the interpreter will look inside the package and find my time.py
modules before it comes across the standard time
module.
有什么办法解决吗?这是不可以的情况,并且模块名称不能重复使用吗?
Is there any way around this? Is this a no-no situation and should modules names not be reused?
任何有关封装哲学的解决方案和意见在这里都将是有用的.
Any solutions and opinions on package philosophy would be useful here.
推荐答案
重用标准函数/类/模块/软件包的名称绝不是一个好主意.尽量避免它.但是,有适合您情况的解决方法.
Reusing names of standard functions/classes/modules/packages is never a good idea. Try to avoid it as much as possible. However there are clean workarounds to your situation.
您看到的导入SWS.time
而不是stdlib time
的行为是由于import
的语义在古代python版本(2.x)中引起的.要修复它,请添加:
The behaviour you see, importing your SWS.time
instead of the stdlib time
, is due to the semantics of import
in ancient python versions (2.x). To fix it add:
from __future__ import absolute_import
位于文件的最顶部.这会将import
的语义更改为python3.x的语义,这更加明智.在这种情况下,语句:
at the very top of the file. This will change the semantics of import
to that of python3.x, which are much more sensible. In that case the statement:
import time
将仅引用顶级模块.因此,在执行包内的导入操作时,解释器将不考虑您的SWS.time
模块,但是它将仅使用标准库之一.
Will only refer to a top-level module. So the interpreter will not consider your SWS.time
module when executing that import inside the package, but it will only use the standard library one.
如果模块内部您的软件包需要导入SWS.time
,则可以选择:
If a module inside your package needs to import SWS.time
you have the choice of:
-
使用显式相对导入:
from . import time
使用绝对导入:
Using an absolute import:
import SWS.time as time
因此,您的foo.py
类似于:
from __future__ import absolute_import
import time
from . import time as SWS_time
这篇关于具有相同名称的Python模块(即,重复使用软件包中的标准模块名称)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!