SoFunction
Updated on 2024-11-20

Comparison of Python's built-in functions locals and globals

These two functions mainly provide, dictionary based access to local and global variables. While understanding these two functions, let's first understand the concept of namespaces in python.Python uses something called namespaces to keep track of variables. A namespace is just a dictionary whose keywords are the variable names, and the values of the dictionary are the values of those variables. In fact, namespaces can be accessed like Python's dictionary

Each function has its own namespace, called the local namespace, which records the function's variables, including the function's arguments and locally defined variables. Each module has its own namespace, called the global namespace, which records the variables of the module, including functions, classes, other imported modules, module-level variables and constants. There is also the built-in namespace, which can be accessed by any module, and which holds built-in functions and exceptions.

When a line of code wants to use the value of variable x, Python goes to all available namespaces and looks up the variable in the following order:

1. Local namespace - Specifically refers to the method of the current function or class. If a function defines a local variable x, Python will use that variable and then stop searching.

2. Global namespace - refers specifically to the current module. If a module defines a variable, function, or class named x, Python will use that variable and stop searching.

3. Built-in namespaces - global to every module. As a last-ditch attempt, Python will assume that x is a built-in function or variable.

If Python doesn't 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 local variable function locals (locals returns a dictionary of name/value pairs.) :

def foo(arg, a):
    x = 1
    y = 'xxxxxx'
    for i in range(10):
        j = 1
        k = i
    print(locals())
Printing results of #called functions
foo(1,2)
[python@master test]$ python3  
{'arg': 1, 'a': 2, 'x': 1, 'y': 'xxxxxx', 'i': 9, 'j': 1, 'k': 9}

locals are read-only and cannot be modified, whereas globals can be modified for a reason:

locals() doesn't actually return a local namespace, it returns a copy. So modifying it modifies the copy and has no effect on the value of the variable in the actual local namespace.

globals() returns the actual global namespace, not a copy: the exact opposite behavior of locals.

So any changes to the dictionary returned by globals will directly affect the values of the global variables.

#coding:utf-8  
'''This is my first python program!'''  
z = 7 # Define global variables
def foo(arg):  
  x = 1  
  print(locals()) 
  print ('x=',x) 
  locals()['x'] = 2 # Modifies a copy of the local namespace, while the values of the variables in the actual local namespace are not affected.
  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 the variable z
print(globals()) 
print("z=",z) 
[python@master test]$ python3  
{'arg': 3, 'x': 1}
x= 1
{'arg': 3, 'x': 1}
x= 1
{'__name__': '__main__', '__doc__': 'This is my first python program!', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb2f23db400>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '', '__cached__': None, 'z': 7, 'foo': <function foo at 0x7fb2f245d1e0>}
z= 7
{'__name__': '__main__', '__doc__': 'This is my first python program!', '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb2f23db400>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '', '__cached__': None, 'z': 8, 'foo': <function foo at 0x7fb2f245d1e0>}
z= 8

This is the whole content of this article.