This article introduces the search order of Python function scope for your reference. The specific content is as follows
1. What is LEGB?
L:local function internal scope
E:enclosing function internal scope and embedded function Inter
G:global global scope
B:build-in built-in scope
2.LEGBWhat is it used for?
Why do we have to introduce this? Or what is their function?
The reason is because when we learn Python functions, we often encounter many domain problems, all variables, internal Variables, internally embedded functions, etc. How does Python find them? And in what order does Python search? Here is a sequence explanation
3. What is the sequence
Like the name, Python’s search in functions is divided into 4 types, called LEGB, which is exactly according to Search in this order.
First, it is local, first search inside the function
Then, it is enclosing, and then search between the inside of the function and the embedded function (referring to defining a function again inside the function)
Secondly, it is global , search global
Finally, it is build-in, built-in scope
4. Example
ex1
passline = 60 def func(val): if val >= passline: print('pass') else: print('failed') func(89) '''''''''''' pass [Finished in 0.2s] ''''''''''''
The Python function first searches for local. There is no definition of passline in the local variable scope. Then it is found that there is no embedded function inside the function. At this time, Python starts to search for global. The definition of passline is found globally and called.
ex2
##
def Max(val1, val2): return max(val1, val2) print(Max(90, 100)) ''''''''' 100 [Finished in 0.1s] '''''''''