問題描述
假設我有一個包含模塊的包:
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
這篇關于具有相同名稱的 Python 模塊(即在包中重用標準模塊名稱)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!