Python3 namespace and scope | rookie tutorial (seventeen)

Table of contents

1. Namespace

(1) Introduction

1. Namespace (Namespace) is a mapping from name to object. Most namespaces are implemented through Python dictionaries.

2. Namespaces provide a way to avoid name conflicts in projects.

3. Each namespace is independent and has no relationship, so a namespace cannot have duplicate names, but different namespaces can have duplicate names without any impact.

4. Let us give 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.

 (2) There are generally three namespaces

1. Built-in names (built-in names)

2. Global names

3. Local names

 (3) Namespace search order:

 (4) Namespace life cycle

 Two, scope

(1) Introduction

(2) Python has four scopes:

1、L(Local)

2、E(Enclosing)

3、G(Global)

4、B(Built-in)

(3) Rule order: L –> E –> G –> B.

1. If you can’t find it locally, you will search it locally (such as closures), and if you can’t find it again, you will search it globally, and then you will find it in the built-in.

 2. The built-in scope is realized through a standard module named builtin, but the variable name itself is not put into the built-in scope, so this file must be imported to be able to use it.

3. In Python3.0, you can use the following code to see which variables are predefined:

 4. Only modules, classes, and functions (def, lambda) in Python will introduce new scopes. Other code blocks (such as if/elif/else/, try/except, for/while, etc.) ) will not introduce a new scope, that is to say, the variables defined in these statements can also be accessed externally, as shown in the following code:

(4) Global variables and local variables

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

2. Local variables can only be accessed within the function in which they are declared, while global variables can be accessed throughout the program.

3. When calling a function, all variable names declared in the function will be added to the scope.

 (5) global and nonlocal keywords

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

2. The following example modifies the global variable num:

3. If you want to modify variables in the nested scope (enclosing scope, outer non-global scope), you need the nonlocal keyword

4. There is another special case, assuming the following code is run:


1. Namespace

(1) Introduction

1. Namespace (Namespace) is a mapping from name to object. Most namespaces are implemented through Python dictionaries.

2. Namespaces provide a way to avoid name conflicts in projects.

3. Each namespace is independent and has no relationship, so a namespace cannot have duplicate names, but different namespaces can have duplicate names without any impact.

4. Let us give 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.

 (2) There are generally three namespaces

1. Built-in names (built-in names )

Python language built-in names, such as function names abs, char and exception names BaseException, Exception and so on.

2. Global names

The name defined in the module records the variables of the module, including functions, classes, other imported modules, module-level variables and constants.

3. Local names

The name defined in the function records the variables of the function, including the parameters of the function and locally defined variables. (also defined in the class)

 (3) Namespace search order:

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

If the variable runoob cannot be found, it will give up and raise a NameError:

NameError: name 'runoob' is not defined。

 (4) 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.

 As shown in the figure below, the same object name can exist in multiple namespaces.

 Two, scope

(1) Introduction

1. The scope is that a Python program can directly access the text area of ​​the namespace.

2. In a python program, if you directly access a variable, you will visit all scopes from inside to outside until you find it, otherwise an undefined error will be reported.

3. In Python, the variables of the program are not accessible at any location, and the access permission depends on where the variable is assigned.

4. The scope of a variable determines which part of the program can access which specific variable name.

(2) Python has four scopes:

1、L(Local)

The innermost layer contains local variables, such as inside a function/method.

2、E(Enclosing)

Contains variables that are neither local (non-local) nor global (non-global). For example, two nested functions, a function (or class) A contains a function B, then for the name in B, the scope in A is nonlocal.

3、G(Global)

The outermost layer of the current script, such as the global variables of the current module.

4、B(Built-in)

Contains built-in variables/keywords, etc., and is searched last.

(3) Rule order: L –> E –> G –> B.

1. If you can’t find it locally, you will search it locally (such as closures), and if you can’t find it again, you will search it globally, and then you will find it in the built-in.

 Example:

g_count = 0 # global scope 
def outer(): o_count = 1 # 
    def inner() 
    in functions outside the closure function : 
        i_count = 2 # local scope

 2. The built-in scope is realized through a standard module named builtin, but the variable name itself is not put into the built-in scope, so this file must be imported to be able to use it.

3. In Python3.0, you can use the following code to see which variables are predefined:

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

 4. Only modules, classes, and functions (def, lambda) in Python will introduce new scopes. Other code blocks (such as if/elif/else/, try/except, for/while, etc.) ) will not introduce a new scope, that is to say, the variables defined in these statements can also be accessed externally, as shown in the following code:

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

The msg variable in the instance is defined in the if statement block, but it can still be accessed from the outside.

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

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

 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.

(4) Global variables and local variables

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

2. Local variables can only be accessed within the function in which they are declared, while global variables can be accessed throughout the program.

3. When calling a function, all variable names declared in the function will be added to the scope.

Example:

 The output of the above example:

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

 (5) global and nonlocal keywords

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

2. The following example modifies the global variable num:

 The output of the above example:

1
123
123

3. If you want to modify variables in the nested scope (enclosing scope, outer non-global scope), you need the nonlocal keyword

Example:

 The output of the above example:

100
100

4. There is another special case, assuming the following code is run:

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

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    test()
  File "test.py", line 5, in test
    a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment

The error message is a local scope reference error, because a in the test function uses a local, undefined, and cannot be modified.

Modify a to be a global variable:

 It can also be passed as a function parameter:

 

Guess you like

Origin blog.csdn.net/wuds_158/article/details/131494758