2010-01-31 65 views
3

我剛剛在comp.lang.python下面發佈了查詢,但是我覺得這種問題在這裏有一些權利堆棧溢出也是如此,以便重複。本質:爲什麼'builtins'在Python 3中有兩種截然不同的解釋?在python 3內建兩個相互矛盾的含義(python 3.1,python 3k,python3000)

我會很樂意接受什麼這個 句話,從http://celabs.com/python-3.1/reference/executionmodel.html收集任何評論, 意在表示,爲什麼神決定這是要走的路。我 預計這個傢伙叫凱Schluehr將有發言權上,或 可能連BDFL會在意發音__builtins__他fallovers,追隨者和fellownerds ::

 
    The built-in namespace associated with the execution of 
    a code block is actually found by looking up the name 
    __builtins__ in its global namespace; this should be a 
    dictionary or a module (in the latter case the module’s 
    dictionary is used). By default, when in the __main__ 
    module, __builtins__ is the built-in module builtins; 
    when in any other module, __builtins__ is an alias for 
    the dictionary of the builtins module itself. 
    __builtins__ can be set to a user-created dictionary to 
    create a weak form of restricted execution. 

它用來作 正確的方法至少有兩個不同的詞, 'builtin'(單數)和'builtins'(複數), 中的一部分以模塊和字典形式存在(?只是猜測?)。現在 只有builtins,所以幸運的是,單數和複數之間的矛盾已經消失了。

但爲什麼__builtins__改變其含義取決於這是否 是「腳本」(即他的名字是 目前,調用python foobar.py當模塊)的範圍或者這是否是第二模塊的 範圍(進口或執行,直接或 間接,由foobar.py)?我無法理解這背後的推理 ,並發現它非常混亂。

理由:爲什麼我照顧-i希望能夠爲「一個Python模塊的出口名稱未標記的私人 全局命名空間(下劃線 前綴),我通過exec(compile(get (locator), locator, 'exec'), R)執行,其中R是應該去 保存所述模塊的私人名稱'。它有點神祕,但 基本的練習是旁路Python的導入系統,並得到similr 結果......它是所有關於注入全局名稱和 模塊全局名稱空間。

回答

1

getattr(__builtins__, '__dict__', __builtins__)應該給你,你要更新到「出口名稱全局命名空間」,__builtins__是否是字典的字典(那麼它沒有一個__dict__屬性使getattr返回第三個參數,這是字典__builtins__本身)或模塊(然後確實具有該屬性並且getattr返回它)。這是解決方法。至於爲什麼Python被記錄爲以需要這種糾結解決方法的方式工作,我將它歸類爲實現問題出現在用戶可見(且實際記錄)級別(嘆氣)的不幸案例。可惜我們並沒有想到要將它轉移到Python 3中,但現在做出向後不兼容的更改爲時已晚:-(。

+0

非常感謝這個快速而簡單的解決方案。有點爲我尋找。 – flow 2010-02-01 18:23:32