Python3 Namespaces and Scope
Namespacing
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。
A namespace is a mapping from names to objects; most namespaces are implemented with Python dictionaries.
Namespaces provide a way to avoid name conflicts in a project. Each namespace is independent and unrelated, so there cannot be duplicate names within one namespace, but different namespaces can reuse names with no effect.
Let's give an example in a computer system: a folder (directory) can contain multiple subfolders; each subfolder cannot have the same file name, but files in different subfolders can have the same name.

There are generally three kinds of namespaces:
- Built-in names (built-in names), names built into the Python language, such as the function names abs and char and the exception names BaseException and Exception.
- Global names (global names), names defined in a module, recording the module's variables, including functions, classes, other imported modules, module-level variables and constants.
- Local names (local names), names defined in a function, recording the function's variables, including its parameters and locally defined variables (the same applies to those defined in a class).

Namespace lookup order:
Suppose we want to use the variable runoob; Python's lookup order is:Local namespace -> Global namespace -> Built-in namespace。
If the variable runoob cannot be found, it gives up the lookup and raises a NameError exception:
NameError: name 'runoob' is not defined。
Namespace lifetime:
The lifetime of a namespace depends on the scope of the object; when the object finishes executing, the lifetime of that namespace ends.
Therefore, we cannot access objects in an inner namespace from an outer namespace.
Example
var1 is a global name
var1
=
5
def
some_func
(
)
:
var2 is a local name
var2
=
6
def
some_inner_func
(
)
:
var3 is a nested local name
var3
=
7
As shown below, the same object name can exist in multiple namespaces.

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.
A scope is the textual region of a Python program where a namespace can be accessed directly.
In a Python program, accessing a variable directly searches all scopes from the inside out until it is found; otherwise an undefined error is reported.
In Python, the variables of a program are not accessible everywhere; access depends on where the variable was assigned.
The scope of a variable determines which part of the program can access that particular variable name.
Python has four kinds of scope:
There are four scopes:
- L(Local): The innermost one, containing local variables, such as inside a function or method.
- E(Enclosing): Contains variables that are neither local (non-local) nor global (non-global). For example, with two nested functions, if a function (or class) A contains a function B, then for names in B the scope in A is nonlocal.
- G(Global): The outermost level of the current script, such as the global variables of the current module.
- B(Built-in): Contains built-in variables and keywords, and is searched last.
The LEGB rule (Local, Enclosing, Global, Built-in): the order in which Python looks up variables is: L –> E –> G –> B。
- Local: The local scope of the current function.
- Enclosing: The scope of the outer function containing the current function (if there are nested functions).
- Global: The global scope of the current module.
- Built-in: Python's built-in scope.
If it is not found locally, it looks in the enclosing local scope (for example a closure), then in the global scope, and finally in the built-in scope.

g_count = 0 # 全局作用域
def outer():
o_count = 1 # 闭包函数外的函数中
def inner():
i_count = 2 # 局部作用域
The built-in scope is implemented through a standard module named builtin, but that variable name itself is not placed in the built-in scope, so you must import this file to use it. In Python 3.0 you can use the following code to see exactly which variables are predefined:
>>> import builtins
>>> dir(builtins)
In Python, only modules, classes and functions (def, lambda) introduce new scopes; other code blocks (such as if/elif/else/, try/except, for/while) do not introduce new scopes, which means variables defined inside those statements can also be accessed outside, as in the following code:
>>> if True:
... msg = 'I am from Runoob'
...
>>> msg
'I am from Runoob'
>>>
In the example the msg variable is defined inside an if block, but it can still be accessed outside.
If msg is defined inside a function, it is a local variable and cannot be accessed outside:
>>> def test():
... msg_inner = 'I am from Runoob'
...
>>> msg_inner
Traceback (most recent call last):
File "", line 1, in
NameError: name 'msg_inner' is not defined
>>>
The error message shows that msg_inner is undefined and cannot be used, because it is a local variable usable only inside the function.
Global and local variables
Variables defined inside a function have a local scope; those defined outside have a global scope.
Local variables can only be accessed inside the function where they are declared, while global variables can be accessed throughout the whole program.
Variables declared inside a function are valid only in the function's inner scope; when the function is called these inner variables are added to that scope and do not affect variables with the same name outside the function, as in the following example:
Example (Python 3.0+)
#!/usr/bin/python3
total
=
0
This is a global variable
Function description can be written
def
sum
(
arg1
,
arg2
)
:
# Return the sum of 2 arguments."
total
=
arg1
arg2
total is a local variable here.
(
"
Inside the function it is a local variable :
"
,
total
)
return
total
# Call the sum function
sum
(
10
,
20
)
(
"
Outside the function it is a global variable :
"
,
total
)
The example above produces the following output:
函数内是局部变量 : 30
函数外是全局变量 : 0
1. Global variables: variables defined outside functions can be accessed throughout the whole file. Variables defined outside a function are visible to all functions, unless a local variable of the same name is defined inside the function.
Example
x
=
10
Global Variables
def
my_function
(
)
:
(
x
)
Can access the global variable x
my_function
(
)
Outputs 10
2. Local variables: variables defined inside a function are valid only inside it and cannot be accessed outside. Local variables take precedence over global ones, so if a local and a global variable share a name, the function uses the local one.
Example
def
my_function
(
)
:
x
=
5
local variables
(
x
)
Access the local variable x
my_function
(
)
Outputs 5
(
x
)
Error: NameError: name 'x' is not defined
The global and nonlocal keywords
When an inner scope wants to modify a variable from an outer scope, the global and nonlocal keywords are needed.
The following example modifies the global variable num:
Example (Python 3.0+)
#!/usr/bin/python3
num
=
1
def
fun1
(
)
:
global
num
It must be declared with the global keyword
(
num
)
num
=
123
(
num
)
fun1
(
)
(
num
)
The example above produces the following output:
1
123
123
To modify a variable in an enclosing scope (an outer non-global scope), the nonlocal keyword is needed, as in the following example:
Example (Python 3.0+)
#!/usr/bin/python3
def
outer
(
)
:
num
=
10
def
inner
(
)
:
nonlocal
num
Declared with the nonlocal keyword
num
=
100
(
num
)
inner
(
)
(
num
)
outer
(
)
The example above produces the following output:
100
100
There is also a special case; suppose the following code is run:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
10
def
test
(
)
:
a
=
a
1
(
a
)
test
(
)
Running the above program gives the following error:
Traceback (most recent call last):
File "test.py", line 7, in
test()
File "test.py", line 5, in test
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
The error is a local scope reference error, because a in the test function is treated as local, undefined and cannot be modified.
Make a a global variable:
Example
#!/usr/bin/python3
a
=
10
def
test
(
)
:
global
a
a
=
a
1
(
a
)
test
(
)
The execution output is:
11
It can also be passed through function parameters:
Example (Python 3.0+)
#!/usr/bin/python3
a
=
10
def
test
(
a
)
:
a
=
a
1
(
a
)
test
(
a
)
The execution output is:
11
Summary
- Global VariablesDefined outside a function, accessible throughout the whole file.
- local variablesDefined inside a function, accessible only inside it.
- Use
globalCan modify global variables inside a function. - Use
nonlocalCan modify variables of an outer function inside a nested function.