These two functions mainly provide a dictionary-based way to access local and global variables.

When understanding these two functions, first let's understand the concept of namespaces in Python. Python uses something called a namespace to record the tracks of variables. A namespace is just a dictionary; its keys are variable names, and the dictionary's values are the values of those variables.

Actually, namespaces can be accessed just like Python dictionaries.

Each function has its own namespace, called the local namespace, which records the function's variables, including its parameters and locally defined variables. Each module has its own namespace, called the global namespace, which records the module's variables, including functions, classes, other imported modules, module-level variables and constants. There is also the built-in namespace, which any module can access; it stores built-in functions and exceptions.

When a line of code needs to use the value of variable x, Python searches through all available namespaces for the variable, in the following order:

  • 1. Local namespace- Specifically the current function or a method of the class. If the function defines a local variable x, Python will use this variable and then stop searching.
  • 2. Global namespace- Specifically the current module. If the module defines a variable, function, or class named x, Python will use this variable and then stop searching.
  • 3. Built-in namespace- It is global to every module. As a last attempt, Python will assume that x is a built-in function or variable.

If Python cannot find x in these namespaces, it will give up searching and raise a NameError exception, while passingThere is no variable named 'x'a message like this.

Example of the local variable 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())
# Print result of calling the function
foo(1,2)
#{'k': 9, 'j': 1, 'i': 9, 'y': 'xxxxxx', 'x': 1, 'a': 2, 'arg': 1}

from module importandimport moduleThe difference between them. With import module, the module itself is imported, but it maintains its own namespace, which is why you need to use the module name to access its functions or attributes (module.function). But with from module import, you are actually importing the specified functions and attributes from another module into your own namespace, which is why you can access them directly without needing to reference the module they come from.

locals is read-only, globals is not.

locals cannot be modified, globals can be modified, for the following reason:

  • locals()Actually, (locals) does not return the local namespace; it returns a copy. So modifying it modifies the copy, and has no effect on the actual variable values in the local namespace.
  • globals() returns the actual global namespace, not a copy, which is completely opposite to the behavior of locals.

Therefore, any modification to the dictionary returned by globals will 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 # What is modified is the copy of the local namespace, and there is no effect on the actual variable values in the local namespace.
    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 )

The output result is:

{'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 link:

https://blog.csdn.net/scelong/article/details/6977867

https://blog.csdn.net/sxingming/article/details/52061630