[2020Python cultivation 17] Introduction to Python syntax - namespace and scope

[directory]

1, Namespace

1. Built in namespace

2. Global namespace

3. Local namespace

2, Scope

1. Global scope and local scope

2. Scope and priority of name search

 

1, Namespace

Namespace: the place where names are stored. It is the division of stack area.

Once you have a namespace, you can store the same name in the stack area. There are three types of namespace: built-in namespace, global namespace and local namespace


L -- Local(function); namespace within function
E -- enclosing function locales; the namespace of an external nested function (for example, close)
G -- Global(module); the namespace of the module (file) where the function definition is located
B -- Builtin(Python); the namespace of Python's built-in modules

# builtin  B - Builtin(Python);Python Namespace for built-in modules 
# global   G - Global(module);The namespace of the module (file) where the function definition is located
def f1():
    # enclosing  E - Enclosing function locals;Namespace of external nested functions(for example closure)
    def f2():
        # enclosing  E - Enclosing function locals;Namespace of external nested functions(for example closure)
        def f3():
            # local  L - Local(function);Namespace in function
            pass

 

1. Built in namespace

Name of the store: the name of the store is the built-in name of the python interpreter

#Life cycle: generated when the python interpreter is started, and destroyed when the python interpreter is closed

# stay Python Inside the interpreter:
'''
>>> print
<built-in function print>
>>> input
<built-in function input>
'''

 

2. Global namespace

#Stored Name: as long as it is not defined in the function or built-in, the rest is the name of the global namespace
#Life cycle: when python files are executed, they are generated and destroyed after running

That is to say, it is generated / recycled along with the start / completion of python file execution. It is the second namespace to be loaded. The names generated during file execution will be stored in this namespace, as follows:

import sys #Module name sys

x=1 #Variable name x

if x == 1:
    y=2 #Variable name y

def foo(x): #Function name foo
    y=1
    def bar():
        pass

Class Bar: #Class name Bar
    pass

 

3. Local namespace

#Stored Name: the name of the function generated in the process of running function body code when calling the function;

That is, the parameters of the function and the names defined in the function will be stored in the local namespace

#Life cycle: live when calling a function, and destroy when the function is called

def func(a,b):
    pass

func(10,1)
func(11,12)
func(13,14)
func(15,16)
def foo(x):
    y=3 #Function code will be executed when function is called, name x and y Are stored in the function's local namespace

 

4. Namespace load order

The loading order of namespaces is: built-in namespace - > global namespace - > local namespace

 

5. Namespace destroy order

The order of namespace destruction is opposite to that of namespace loading, i.e. local namespace > global namespace > built-in namespace

 

6. Search priority for name

To find a name, you must find it from one of the three namespaces, from the current location to the next level

Built in namespace
Global namespace
Local namespace

(1) If you are currently in a local namespace:

The search order is: local namespace - > global namespace - > built-in namespace - > exception will be thrown if none is found at last

#input=333 the name of the global scope input
def func():
    input=444 ා local name input
    print(input): find input locally

func()

Output results:
444
input=333  #Name of global scope input

def func():
    # input=444  #If there is no local name input, the name input of the global scope will be found
    print(input)

func()

Output result: 333

(2) If you are currently in a global namespace
The search order is: global namespace - > built-in namespace - > exception will be thrown if none is found at last

input=333 ා global variable
def func(): input=444 ා the name of the local scope when the function is called input
 func()
print(input) ා the statement does not belong to the function body and belongs to the global namespace; when the function is called, it has no impact on the statement, so the print function is directly executed, starting from the global namespace, that is, the output global variable input=333 Output results: 333
# input=333
def func(): input=444 func()
print(input) # This statement does not belong to the function body and belongs to the global namespace. When a function is called, it has no impact on the statement, so it directly performs the print function, starting from the global namespace,
If there is no value in the global space, it will be found in the built-in namespace, that is <built-in function input> //Output results:
<built-in function input>

Chestnut 1:

def func():
    print(x)
x=111 # global variable

func()

Chestnut 2: the "nesting" relationship of the namespace is based on the function definition stage, independent of the call location

x=1
def func():
   print(x)


def foo():
    x=222
    func()

foo()

 

Chestnut 3: function nesting definition——

python supports the nested definition of functions. When you search for a name in an embedded function, you will first find the name of your local scope,

Then look up the scope defined by the external nested function layer by layer from the inside out. If not, look up the global scope

 

Run a function first:

def f2():
    input = 333
    print(input)
input = 222 is a global variable. When function f2 is called, find the value in the local space of the function first. If there is a local variable input = 333, print the value.

f2()

Output results:
333

Take the above functions as sub functions, and the nested definition of functions:

input=111
def f1():
    def f2():
        input=333
        print(input)
    input=222

    f2()

f1()  # f1 inserts sub function f2, which is the function body of f1. Therefore, the execution procedure of function call is the same as above

//Output results:
333
input=111
def f1():
    def f2():
        # input=333 #If the local variable is annotated, when f2 is executed, no value can be found in the local space of the function, and it will be found in the function space of the upper layer. There are global variables input=222, execute f2, and output 222
        print(input)
    input=222

    f2()

f1()

//Output results:
222
input=111
def f1():
    def f2():
        # input=333
        print(input)
    # input=222  #If the variables of the local space and the closest global space of f2 are removed, the function f2 will continue to find the value of the next global space when it is executed. If input=111 exists, the output result is 111

    f2()

f1() 

//Output results:
111

Chestnut No. 4: first defined, then used

x=111
def func():
    print(x)
    x=222

func()

# UnboundLocalError: local variable 'x' referenced before assignment 
#    Namely variable x Not defined before use

Modify it as follows:

x=111
def func():
    x = 222
    print(x)

func()

Output results:
222

 

2, Scope

Scope, that is, scope.

1. Global scope and local scope

Global scope: names in global namespace and built-in namespace belong to global scope
1. Global survival (survives the entire execution of the file unless it is deleted)
2. Globally valid: shared by all functions (available anywhere)

x=111 #Global variable, global valid

def foo():
    print(x,id(x))

def bar():
    print(x,id(x))

foo()
bar()

print(x,id(x))

//Output results:
111 140730714743904
111 140730714743904
111 140730714743904

Local scope: names in a local namespace are local
1. Temporary survival: that is, it is generated temporarily when the function is called and released after the function is called
2. Locally valid: can only be used within a function

 

x=100 #The name of the global scope x
def foo():
    x=300 #The name of the local scope x
    print(x) #Partial search x
foo()#The result is 300

 

2. Scope and priority of name search

(please refer to 6. Priority of name search in the first part)

The summary is as follows:

(1) When searching for a name in the local scope, the starting position is the local scope, so first look for the local namespace, and then go to the global scope to find it. First look for the global namespace, and then look for the built-in namespace. Finally, if you don't find it, an exception will be thrown

(2) When looking for a name in the global scope, the starting position is the global scope. So first look for the global namespace, and then look for the built-in namespace. If you don't find it, an exception will be thrown

(3) Tip: you can call the built-in functions locals() and globals() to view the names of local scope and global scope respectively, and the results are all in dictionary format.

The result of locales () viewed in the global scope is equal to global ()

(4) python supports the nested definition of functions. When you search for a name in an embedded function, you will first search for the name of your local scope, and then search for the scope defined by an external nested function layer by layer. If you don't find it, you will search for the global scope (chestnut 4)

(5) No matter how many layers are nested in a function, you can view the name of the global scope. To modify the value of the name in the global namespace in a function, you need to use the global keyword (chestnut 2) when the value is of immutable type

(6) For nested multi-level functions, you can use the nonlocal keyword to declare the name as a scope (not global) defined by the external nested function (chestnut 5)

(7) When the value of the argument is of variable type, the modification of the value in the function body will directly reflect the original value (chestnut 3)

 

Chestnut 1:

x=111

def func():
    x=222

func()
print(x) # It's in global space, so first find it from global space, and it exists x=111,Output result 111


Chestnut 2: if you want to modify the value corresponding to the global name (immutable type) locally, you need to use global to declare the variable as a global variable

x=111

def func():
    global x # statement x This name is the name of the whole situation. Don't create a new name
    x=222

func()
print(x)

//Output results:
222

Chestnut 3: when the value of the argument is of variable type, the modification of the value in the function body will directly reflect the original value

l=[111,222]
def func():
    l.append(333) #l Variable type, no need to declare

func()
print(l)

//Output results:
[111, 222, 333]

Chestnut 4: function nesting definition

x=1
def outer():
    x=2
    def inner(): # Function name inner belong to outer The name of this layer's scope
        x=3
        print('inner x:%s' %x)

    inner()
    print('outer x:%s' %x)

outer() 
#The result is
inner x:3
outer x:2

Chestnut 5: nonlocal (understanding): modify the value corresponding to the name contained in the outer function of the function (immutable type)
For nested multi-level functions, use the nonlocal keyword to declare the name as a scope (not global) from the definition of an external nested function

nonlocal x will start from the outer function of the current function to find the name x layer by layer. If the name x cannot be found all the way to the outer function, an exception will be thrown.

x=0
def f1():
    x=11
    def f2():
        x=22
    f2()
    print('f1 Internal x: ',x)

f1()  #To execute function f1, first find the value in the local space of the function body. If there is x=11, it will be output; if there is x=22 in built-in function f2, it is only useful for f2.

//Output results:
f1 Internal x:  11

 

x=0
def f1():
    x=11
    def f2():
        nonlocal x   #Declare that x=22 in built-in function f2 is not a local variable in built-in function f2. If it belongs to outer function f2, x=22 will overwrite x=11 as the final result.
        x=22
    f2()       #call f2(),modify f1 Name in scope x Value
    print('f1 Internal x: ',x)  #View x in the f1 scope

f1()

//Output results:
f1 Internal x:  22

Tags: Python REST

Posted on Thu, 19 Mar 2020 07:51:10 -0400 by Shrike