YouTip LogoYouTip

Python3 Namespace Scope

# Python3 Namespace and Scope ## Python3.x Python3 Namespace and Scope ## Namespace First, let's 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 currently implemented as Python dictionaries. Namespaces provide a way to avoid name conflicts in a project. Each namespace is independent and has no relationship with others, so there cannot be duplicate names within a single namespace, but different namespaces can have duplicate names without any impact. Let's take an example from a computer system: a folder (directory) can contain multiple subfolders. Each subfolder cannot have files with the same name, but files in different subfolders can have the same name. !(#) Generally, there are three types of namespaces: * **Built-in names**: Names built into the Python language, such as function names like `abs`, `char`, and exception names like `BaseException`, `Exception`, etc. * **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**: Names defined in a function, recording the function's variables, including function parameters and locally defined variables. (Names defined in a class are also local.) !(#) Namespace lookup order: Suppose we want to use the variable ``. Python's lookup order is: **Local namespace -> Global namespace -> Built-in namespace**. If the variable `` cannot be found, it will abandon the search and raise a `NameError` exception: `NameError: name '' is not defined`. Namespace lifecycle: The lifecycle of a namespace depends on the scope of the object. If the object's execution is complete, the lifecycle of that namespace ends. Therefore, we cannot access objects in an inner namespace from an outer namespace. ## Example ```python # var1 is a global name var1 = 5 def some_func(): # var2 is a local name var2 = 6 def some_inner_func(): # var3 is an inner local name var3 = 7 As shown in the diagram 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 a textual region of a Python program where a namespace is directly accessible. In a Python program, directly accessing a variable will search all scopes from the innermost to the outermost until it is found; otherwise, an undefined error will be reported. In Python, a program's variables are not accessible everywhere. Access rights depend on where the variable is assigned. A variable's scope determines which part of the program can access that specific variable name. Python has four types of scopes: * **L (Local)**: The innermost scope, containing local variables, such as inside a function/method. * **E (Enclosing)**: Contains non-local and non-global variables. For example, in two nested functions, if function (or class) A contains function B, then for names in B, the scope in A is nonlocal. * **G (Global)**: The outermost scope of the current script, such as global variables in the current module. * **B (Built-in)**: Contains built-in variables/keywords, etc., and is searched last. LEGB Rule (Local, Enclosing, Global, Built-in): Python searches for variables in the following order: **L -> E -> G -> B**. 1. **Local**: The local scope of the current function. 2. **Enclosing**: The scope of the outer function containing the current function (if there are nested functions). 3. **Global**: The global scope of the current module. 4. **Built-in**: The built-in scope of Python. If not found locally, it will search in the enclosing scope (e.g., closures), then in the global scope, and finally in the built-in scope. !(#) ```python g_count = 0 # Global scope def outer(): o_count = 1 # Enclosing scope (outside the inner function) def inner(): i_count = 2 # Local scope The built-in scope is implemented through a standard module named `builtins`, but this 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 which variables are predefined: ```python >>> import builtins >>> dir(builtins) In Python, only modules (`module`), classes (`class`), and functions (`def`, `lambda`) introduce new scopes. Other code blocks (such as `if/elif/else`, `try/except`, `for/while`, etc.) do not introduce new scopes. This means variables defined within these statements are also accessible from outside, as shown in the following code: ```python >>> if True: ... msg = 'I am from ' ... >>> msg 'I am from ' >>> In the example, the variable `msg` is defined inside the `if` statement block, but it is still accessible from outside. If `msg` is defined inside a function, it becomes a local variable and cannot be accessed from outside: ```python >>> def test(): ... msg_inner = 'I am from ' ... >>> msg_inner Traceback (most recent call last): File "", line 1, in NameError: name 'msg_inner' is not defined >>> From the error message, it indicates that `msg_inner` is undefined and cannot be used because it is a local variable and can only be used inside the function. ### Global and Local Variables Variables defined inside a function have a local scope, while those defined outside a function have a global scope. Local variables can only be accessed within the function where they are declared, while global variables can be accessed throughout the entire program. Variables declared inside a function are only valid within the function's scope. When the function is called, these internal variables are added to the function's internal scope and do not affect variables with the same name outside the function, as shown in the following example: ## Example (Python 3.0+) ```python total = 0 def sum(arg1, arg2): total = arg1 + arg2 print("Inside function, total is local: ", total) return total sum(10, 20) print("Outside function, total is global: ", total) The output of the above example is: Inside function, total is local: 30 Outside function, total is global: 0 1. **Global variables**: Variables defined outside a function can be accessed throughout the file. Variables defined outside a function are visible to all functions unless a local variable with the same name is defined inside the function. ## Example ```python x = 10 # Global variable def my_function(): print(x) # Can access the global variable x my_function() # Outputs 10 2. **Local variables**: Variables defined inside a function are only valid within the function and cannot be accessed from outside. Local variables have higher priority than global variables, so if a local variable and a global variable have the same name, the function will use the local variable. ## Example ```python def my_function(): x = 5 # Local variable print(x) # Accesses the local variable x my_function() # Outputs 5 print(x) # Error: NameError: name 'x' is not defined ### The `global` and `nonlocal` Keywords When an inner scope wants to modify a variable in an outer scope, the `global` and `nonlocal` keywords are used. The following example modifies the global variable `num`: ## Example (Python 3.0+) ```python num = 1 def fun1(): global num print(num) num = 123 print(num) fun1() print(num) The output of the above example is: 1 123 123 If you want to modify a variable in an enclosing scope (the outer non-global scope), the `nonlocal` keyword is needed, as shown in the following example: ## Example (Python 3.0+) ```python def outer(): num = 10 def inner(): nonlocal num num = 100 print(num) inner() print(num) outer() The output of the above example is: 100 100 There is also a special case. Suppose the following code is run: ## Example (Python 3.0+) ```python 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 "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 message indicates a local scope reference error because the `a` in the `test` function is local and undefined, so it cannot be modified. To modify `a` as a global variable: ## Example ```python a = 10 def test(): global a a = a + 1 print(a) test() The output is: 11 Alternatively, you can pass it through function parameters: ## Example (Python 3.0+) ```python a = 10 def test(a): a = a + 1 print(a) test(a) The output is: 11 ### Summary * **Global variables** are defined outside a function and can be accessed throughout the file. * **Local variables** are defined inside a function and can only be accessed within the function. * Use `global` to modify a global variable inside a function. * Use `nonlocal` to modify a variable from an outer function in a nested function.
← Ng Ng Class EvenPython3 Assert β†’