Python introductory tutorial | Python namespace and scope

Namespaces

Let’s first look at a passage from the official documentation:

A namespace is a mapping from names to objects.Most namespaces are
currently implemented as Python dictionaries。

Chinese translation : Namespace is a mapping from names to objects. Most namespaces are implemented through Python dictionaries.

Namespaces provide a way to avoid name conflicts in a project. Each namespace is independent and has no relationship, so there cannot be duplicate names in one namespace, but different namespaces can have duplicate names without any impact.

Let's take an example in a computer system. A folder (directory) can contain multiple folders. Each folder cannot have the same file name, but files in different folders can have the same name.
Insert image description here
There are generally three namespaces:

  • Built-in names , built-in names in the Python language, such as function names abs, char and exception names BaseException, Exception, etc.
  • Global names (global names) , names defined in the module, record the variables of the module, including functions, classes, other imported modules, module-level variables and constants.
  • Local names (local names) , names defined in a function, record the variables of the function, including function parameters and locally defined variables. (It is also defined in the class)

Insert image description here
Namespace search order:

Assuming we want to use the variable tarzan, Python's search order is: local namespace -> global namespace -> built-in namespace.

If the variable tarzan is not found, it will give up the search and raise a NameError exception:

NameError: name ‘tarzan’ is not defined。

Namespace life cycle:

The life cycle of a namespace depends on the scope of the object. If the object execution is completed, the life cycle of the namespace ends.

Therefore, we cannot access objects of the inner namespace from the outer namespace.

# var1 是全局名称
var1 = 5
def some_func(): 
  
    # var2 是局部名称
    var2 = 6
    def some_inner_func(): 
  
        # var3 是内嵌的局部名称
        var3 = 7

As shown in the figure below, the same object name can exist in multiple namespaces.
Insert image description here

Scope

A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.

Chinese translation: Scope is the text area of ​​a Python program where the namespace can be directly accessed. "Directly accessible" here means that an unqualified reference to a name attempts to look up that name in the namespace.

In a python program, if you directly access a variable, all scopes will be accessed from the inside to the outside until it is found, otherwise an undefined error will be reported.

In Python, program variables are not accessible everywhere. Access permissions depend on where the variable is assigned a value.

The scope of a variable determines which part of the program can access a specific variable name. There are 4 types of scopes in Python, namely:

Four scopes:

L (Local) : The innermost layer contains local variables, such as inside a function/method.
E (Enclosing) : Contains non-local (non-local) and non-global (non-global) variables. For example, if there are two nested functions, and one function (or class) A contains a function B, then for the name in B, the scope in A is nonlocal.
G (Global) : The outermost layer of the current script, such as the global variables of the current module.
B (Built-in) : Contains built-in variables/keywords, etc., which are finally searched.
Rule order: L –> E –> G –> B.

If it is not found locally, it will be searched locally (such as closures). If it is not found, it will be searched globally, and then it will be searched in the built-in.
Insert image description here

g_count = 0  # 全局作用域
def outer():
    o_count = 1  # 闭包函数外的函数中
    def inner():
        i_count = 2  # 局部作用域

The built-in scope is implemented through a standard module called builtin, but the variable name itself is not placed in the built-in scope, so this file must be imported to use it. In Python 3.0, you can use the following code to see which variables are predefined:
interactive

>>> import builtins
>>> dir(builtins)

In Python, only modules, classes and functions (def, lambda) will introduce new scopes. Other code blocks (such as if/elif/else/, try/except, for/while, etc.) are No new scope will be introduced, which means that the variables defined in these statements can also be accessed from the outside, as shown in the following code:

>>> if True:
...  msg = 'I am from China'
... 
>>> msg
'I am from China'
>>> 

In the example, the msg variable is defined in the if statement block, but it is still accessible from the outside.

If msg is defined in a function, it is a local variable and cannot be accessed from outside:

>>> def test():
...     msg_inner = 'I am from China'
... 
>>> msg_inner
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'msg_inner' is not defined
>>> 

Judging from the error message, it shows that msg_inner is undefined and cannot be used because it is a local variable and can only be used within the function.

Global variables and local variables

Variables defined inside a function have a local scope, and variables defined outside a function have a global scope.

Local variables can only be accessed within the function in which they are declared, while global variables can be accessed throughout the program. When a function is called, all variable names declared within the function will be added to the scope. Examples below:

#!/usr/bin/python3
 
total = 0 # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
    #返回2个参数的和."
    total = arg1 + arg2 # total在这里是局部变量.
    print ("函数内是局部变量 : ", total)
    return total
 
#调用sum函数
sum( 10, 20 )
print ("函数外是全局变量 : ", total)

The output of the above example is:

Local variables inside the function: 30
Global variables outside the function: 0

global and nonlocal keywords

When the inner scope wants to modify the variables of the outer scope, the global and nonlocal keywords are used.

The following example modifies the global variable num:

#!/usr/bin/python3
 
num = 1
def fun1():
    global num  # 需要使用 global 关键字声明
    print(num) 
    num = 123
    print(num)
fun1()
print(num)

The output of the above example is:

1
123
123

#!/usr/bin/python3
 
def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()

The output of the above example is:

100
100

There is also a special case, assuming that the following code is run:

#!/usr/bin/python3
 
a = 10
def test():
    a = a + 1
    print(a)
test()

When the above program is executed, the error message is as follows:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\test.py", line 7, in <module>
    test()
  File "C:\Users\Lenovo\Desktop\test.py", line 5, in test
    a = a + 1
        ^
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value

The error message is a local scope reference error, because a in the test function is local, undefined, and cannot be modified.
Modify a as a global variable:

#!/usr/bin/python3
 
a = 10
def test():
    global a
    a = a + 1
    print(a)
test()

The execution output is:

11

It can also be passed via function parameters:

#!/usr/bin/python3
 
a = 10
def test(a):
    a = a + 1
    print(a)
test(a)

The execution output is:

11

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/133198542