問題描述
我有一個關(guān)于進口的問題.這個問題可能看起來有點做作,但它的目的是探索對包中的所有導入使用絕對導入的限制.PEP8 強烈反對相對導入(和 Google Python 風格指南 說永遠不要使用它們).
假設(shè)您有兩個同名的大型軟件包,并且都使用符合 PEP8 的絕對導入:
<上一頁>/pkg1mod1.py(包含絕對導入:'import pkg1.mod2')模組2.py.../pkg1mod1.py(包含絕對導入:'import pkg1.mod3')模組3.py...另外說你正在處理一個 Python 項目,你想在其中使用這兩個包.例如,如果您想在一個項目中使用同一包的兩個版本,則可能會出現(xiàn)這種情況.
有沒有辦法將這兩個包合并到您的項目層次結(jié)構(gòu)中,以便您可以在整個項目中自由使用這兩個包中的模塊?
對于解決方案,可以使用導入別名和臨時修改 sys.path 之類的操作.但是不可以隨便改動一個包目錄的內(nèi)容.
簡短的回答是否定的,Python 不接受兩個同名的包.(有些東西稱為命名空間包",它允許在多個目錄中實現(xiàn)單個包,但它們需要設(shè)置所涉及的包以相互協(xié)作.
PEP 8 不鼓勵顯式相對導入的方式是其更值得懷疑的建議之一,正是因為它使得重命名包以避免命名沖突變得更加困難.如果這兩個包使用相對導入,您可以重命名其中一個或?qū)⑵淝短自诹硪粋€包中并完成.
import aliases 在這里對您沒有幫助,因為重要的是以 sys.modules
結(jié)尾的名稱,并且它使用導入的模塊名稱,而不是最終被綁定在導入模塊中.
如果你想獲得真正的異國情調(diào),你可以編寫自己的導入器(參見 PEP 302 和 3.x importlib
文檔).如果你決定走那么遠,你幾乎可以做任何你想做的事情.
I have a question about imports. The question might seem a bit contrived, but its purpose is to explore the limitations of using absolute imports for all imports in a package. PEP8 highly discourages relative imports (edit: and the Google Python Style Guide says never to use them).
Say you are given two large-ish packages that both have the same name and that both use absolute imports in accordance with PEP8:
/pkg1 mod1.py (contains an absolute import: 'import pkg1.mod2') mod2.py ... /pkg1 mod1.py (contains an absolute import: 'import pkg1.mod3') mod3.py ...
Also say you are working on a Python project in which you'd like to use both packages. This could come up, say, if you want to use two versions of the same package in a project.
Is there a way to incorporate both packages into your project hierarchy so that you can freely use modules from both packages throughout your project?
For the solution it's acceptable to do things like use import aliases and modify sys.path temporarily. But it's not okay to change the contents of either package directory.
The short answer is no, Python doesn't accept two packages with the same name. (There are things called "namespace packages" that let a single package be implemented over multiple directories but they require the packages involved to be set up to cooperate with each other).
The way PEP 8 discourages explicit relative imports is one of its more questionable pieces of advice, precisely because it makes it harder to rename a package to avoid naming conflicts. If the two packages used relative imports, you could just rename one of them or nest it inside another package and be done with it.
import aliases won't help you here, because it is the name that ends up in sys.modules
that matters, and that uses the name of the module as imported, rather than the name that ends up being bound in the importing module.
If you wanted to get really exotic, you could write your own importer (see PEP 302 and the 3.x importlib
documentation). If you decide to go that far, you can do pretty much anything you want.
這篇關(guān)于是否可以使用兩個具有相同名稱的 Python 包?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!