具有相同名称的 Python 模块(即在包中重用标准模块名称)
问题描述
假设我有一个包含模块的包:
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
,是由于古代 python 中 import
的语义版本(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
将类似于:
So, your foo.py
would be something like:
from __future__ import absolute_import
import time
from . import time as SWS_time
相关文章