2013-10-17 44 views
1

導入模塊,我不知道是否有做類似蟒蛇:在包命名空間

import scipy as sp 
from scipy import interpolate as sp.interpolate 

這是不允許的某些標準方式。

具體做法是:

  1. 我想知道是否有某種原因,爲什麼上面是不允許的。如果我正在開發我自己的包foo,儘可能少地污染它的名稱空間似乎是合理的。

  2. 之類的東西

    import scipy as sp 
    __import__('scipy.interpolate') 
    

    做的工作,但不是所有的美好和文檔建議不要使用__import__,如無絕對必要。同樣

    import importlib 
    import scipy as sp 
    importlib.import_module('scipy.interpolate',sp) 
    

做工作,但它仍然是醜陋的,甚至更長的時間,並把導入庫命名空間中的...

+0

我不認爲它污染了命名空間來使用'進口SciPy的作爲sp'看http://programmers.stackexchange.com/questions/187403/import-module-vs-from-module-import-function – rtrwalker

+0

這不是'導入scipy sp',而是許多導入scipy.xxx,隨後使用導入scipy的積分,插值,信號,...子模塊。我想把它們都放在'sp' – user2340231

回答

0

導入模塊像對待普通對象,所以如果你真的想你可以導入一個模塊,並將其分配到任意變量,像這樣

import scipy as sp 
from scipy import interpolate 
sp.interpolate = interpolate 

sp.interpolate會像預期的那樣,它只是指向每當調用sp.interpolate的內插模塊。他們是同一個對象的下方,即

print sp.interpolate is interpolate 
>>> True 

然後到最後刪除原來的「插值」指針調用

del interpolate 
+1

之下,然後我想'del interpolate'。我想這樣做的原因實際上是爲了防止IDE混淆用戶。如果我讓我的模塊成爲foo,當人們在普通的python IDE中使用foo時,輸入'foo.'就會啓動自動完成任何內容。我不喜歡我用來顯示的所有scipy模塊。特別是,我不喜歡不熟練的用戶想知道他們看作'foo.interpolate'的'interpolate'是否實際上是foo的一部分。大多數IDE似乎不會查看'__all__'並且只能自動擴展官方軟件包界面。 – user2340231

+0

是的,如果你想完全擺脫內插指針,那麼使用'del interpolate',內插模塊將只能通過你定義的'sp.interpolate'指針來使用。 –

+0

我編輯了我的答案並添加了原始插值指針的刪除。如果這回答你的問題,請將其標記爲正確。 –