深入理解Python中命名空間的尋找規則LEGB

來源:互聯網
上載者:User
名字空間

Python 的名字空間是 Python 一個非常核心的內容。
其他語言中如 C 中,變數名是記憶體位址的別名,而在 Python 中,名字是一個字串對象,它與他指向的對象構成一個{name:object}關聯。
Python 由很多名字空間,而 LEGB 則是名字空間的一種尋找規則。
範圍

Python 中name-object的關聯儲存在不同的範圍中,各個不同的範圍是相互獨立的。而我們就在不同的範圍中搜尋name-object。

舉個栗子,來說明範圍是相互獨立的。

In [11]: i = "G"In [12]: def test():      i = "L"      print i, "in locals"  ....:In [13]: test()    L in localsIn [14]: print i, "in globals"    G in globals


在上面的栗子中,我們定義了兩次 i,在 test 函數中是 i-L,在外面是 i-G。為什麼在 test 函數中,我們 i 指向的是對象 L,而在外面,i 指向的則是 G?這就是 LEGB 的作用。
簡述

簡而言之,LEGB 代表名字尋找順序: locals -> enclosing function -> globals -> __builtins__

  • locals 是函數內的名字空間,包括局部變數和形參
  • enclosing 外部嵌套函數的名字空間(閉包中常見)
  • globals 全域變數,函數定義所在模組的名字空間
  • builtins 內建模組的名字空間

所以,在 Python 中檢索一個變數的時候,優先回到 locals 裡面來檢索,檢索不到的情況下會檢索 enclosing ,enclosing 沒有則到 globals 全域變數裡面檢索,最後是到 builtins 裡面來檢索。

當然,因為 builtins 的特殊性,我們可以直接在 builtins 裡面添加變數,這樣就可以在任意模組中訪問變數,不過這種方法太過於變態,不推薦這麼做。
locals,globals

函數的形參跟內部變數都儲存在 locals 中。

In [1]: def f(x):  ...:   a = x  ...:   print a  ...:   print locals()  ...:In [2]: f("hello")hello{'a': 'hello', 'x': 'hello'}

不過在函數內部調用global 聲明的時候,可以將變數儲存在 globals 中

In [6]: def f(x):  ...:   global a  ...:   a = x  ...:   print a  ...:   print locals()  ...:In [7]: f("hello")hello{'x': 'hello'}In [8]: print ahelloIn [9]: print x---------------------------------------------------------------------------NameError                 Traceback (most recent call last) in ()----> 1 print xNameError: name 'x' is not defined

如上面栗子中那樣,在函數中聲明 a 為全域變數,則函數 f 的 locals只有參數 x,而沒有變數,而在外部可以使用變數 a,而使用 x 的時候則是NameError
Enclosed

Enclosing 是外部嵌套函數的名字空間。我們經常在閉包中用到。在 Python3中提供了一個 nonlocal關鍵字來修改外部嵌套函數的名字空間,但是要使用 Python3才有,我等使用 Python2的只能眼饞一下。

In [11]: def outer():  ....:   a_var = 'enclosed value'  ....:   print a_var  ....:   def inner():  ....:     a_var = 'local value'  ....:     print(a_var)  ....:   inner()  ....:   print a_var  ....:In [12]: outer()enclosed valuelocal valueenclosed value

下面的栗子簡單示範一下 nonlocal 的用法,實在 Python3下面才可以正常啟動並執行:

In [1]: a_var = 'global value'In [2]: def outer():  ...:   a_var = "local value"  ...:   print("outer befor", a_var)  ...:   def inner():  ...:     nonlocal a_var  ...:     a_var = "inner value"  ...:     print("in inner():", a_var)  ...:   inner()  ...:   print("outer inner:", a_var)  ...:In [3]: outer()outer befor local valuein inner(): inner valueouter inner: inner valueIn [4]: print(a_var)global value

builtins

builtins 則是內建模組,輕易不要修改

In [19]: b---------------------------------------------------------------------------NameError                 Traceback (most recent call last) in ()----> 1 bNameError: name 'b' is not definedIn [20]: __builtins__.b = "builtins"In [21]: bOut[21]: 'builtins'

上面栗子中在第一次調用b的時候報錯NameError,之後我們修改 builtins 的名字空間,將名字b與值"builtins"進行關聯,就可以正常調用了。這種非常規用法不建議使用。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.