Python Two Built-in Functions: locals and globals
Category Programming Technology
These two functions primarily provide access to local and global variables in a dictionary-based manner.
To understand these functions, first, let's grasp the concept of namespaces in Python. Python uses something called namespaces to keep track of variable traces. A namespace is simply a dictionary where the keys are variable names and the values are the variable values.
In fact, namespaces can be accessed just like dictionaries in Python.
Each function has its own namespace called a local namespace, which records the function's variables, including function parameters and locally defined variables. Each module has its own namespace called a global namespace, which records the module's variables, including functions, classes, other imported modules, module-level variables, and constants. There is also a built-in namespace that any module can access, which contains built-in functions and exceptions.
When a line of code needs to use the value of a variable x, Python searches through all available namespaces in the following order:
-1. Local Namespace - Refers to the current function or class method. If the function defines a local variable x, Python will use this variable and stop searching.
-2. Global Namespace - Refers to the current module. If the module defines a variable named x, function, or class, Python will use this variable and stop searching.
-3. Built-in Namespace - Global to every module. As a last resort, Python will assume x is a built-in function or variable.
If Python cannot find x in these namespaces, it will give up and raise a NameError exception with the message There is no variable named 'x'.
Example of the local variables function locals (locals returns a dictionary of name/value pairs):
Example
def foo(arg, a):
x = 1
y = 'xxxxxx'
for i in range(10):
j = 1
k = i
print(locals())
# Function call print result
foo(1,2)
#{'k': 9, 'j': 1, 'i': 9, 'y': 'xxxxxx', 'x': 1, 'a': 2, 'arg': 1}
The difference between from module import and import module. Using import module, the module itself is imported, but it retains 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, you actually import the specified functions and attributes from another module into your own namespace, which is why you can access them directly without referencing the module they come from.
locals is read-only, globals is not.
locals cannot be modified, globals can be modified, because:
-locals() does not actually return the local namespace; it returns a copy. So modifying it changes the copy, not the actual local namespace variables.
- globals() returns the actual global namespace, not a copy, behaving opposite to locals.
Therefore, any changes to the dictionary returned by globals directly affect the values of global variables.
Example
#!/usr/bin/env python
z = 7 # Define global variable
def foo(arg):
x = 1
print( locals() )
print('x=',x)
locals()['x'] = 2 # Modifying the copy of the local namespace, not the actual local namespace variables.
print( locals() )
print( "x=",x )
foo(3)
print( globals() )
print( 'z=',z )
globals()["z"] = 8 # globals() returns the actual global namespace, modifying the value of variable z
print( globals() )
print( "z=",z )
Output result:
{'x': 1, 'arg': 3}
x= 1
{'x': 1, 'arg': 3}
x= 1
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10b099358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'z': 7, 'foo': <function foo at 0x10ae48e18>}
z= 7
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10b099358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'z': 8, 'foo': <function foo at 0x10ae48e18>}
z= 8
>
Reference links:
https://blog.csdn.net/scelong/article/details/6977867
https://blog.csdn.net/sxingming/article/details/52061630
** Click to share notes
-
-
-