Python built-in functions-locals and globals
These two functions provide dictionary-based access to local and global variables.
To understand these two functions, first understand the concept of namespace in python. Python uses namespace
Something to record the trajectory of a variable. The namespace is just a dictionary. Its key word is the variable name, and its value is the variable
The value of the number. Actually, namespace can be accessed like a Python dictionary
Each function has its own namespace, called a local namespace. It records function variables, including function parameters.
And locally defined variables. Each module has its own namespace, which is called a global namespace. It records module changes.
Data volume, including functions, classes, other imported modules, module-level variables, and constants. There is also a built-in namespace, any model
Block can be accessed, it stores built-in functions and exceptions.
When a line of code uses the value of variable x, Python searches for variables in all available namespaces in the following order:
1. Local namespace-This refers to the method of the current function or class. If the function defines a local variable x, Python uses
This variable, and then stop searching.
2. Global namespace-This refers to the current module. If the module defines a variable named x, function or class, Python
The variable is used to stop searching.
3. built-in namespace-Global for each module. As a final attempt, Python assumes that x is a built-in function or variable.
If Python cannot find x in these namespaces, it will discard the lookup and raise a NameError exception.
There is no variable named 'x.
# Example of the local variable function locals (locals returns a name/value pair dictionary .) :
Def foo (arg, a): x = 1y = 'xxxxxx' for I in range (10): j = 1 k = iprint locals () # Call the function to print the result foo () # {'A': 2, 'I': 9, 'K': 9, 'J': 1, 'arg ': 1, 'y': 'xxxxxx', 'x': 1}
The differences between from module import and import module. Use the import module to import the module itself,
However, it maintains its own namespace, Which is why you need to use the module name to access its functions or attributes (module. function)
. However, using from module import actually imports the specified functions and attributes into your own name from another module.
Space, which is why you can directly access them without referencing the modules from which they are sourced.
Locals is read-only and globals is not