Master Python’s locals() and globals(): When and How to Use Them
Learn the essential differences between Python’s locals() and globals() functions, how they reveal variable scopes, how to modify them safely, and practical use cases such as dynamic variable creation, debugging, and performance considerations, all illustrated with clear code examples.
If you want to learn Python, understanding the locals() and globals() functions is a crucial concept.
Once you master locals() and globals() , you can:
Modify variables dynamically.
Understand variable scope like a professional.
Write more powerful and flexible code.
Let’s dive in.
locals() and globals() – What Are They?
Python stores variables in different places depending on where they are created. locals() shows only the variables in the current function or scope, while globals() shows variables at the module (global) level, even outside functions.
Example:
<code>x = "global"
def my_func():
y = "local"
print(locals())
print(globals())
my_func()</code>Output:
<code>{'y': 'local'}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'script.py', '__cached__': None, 'x': 'global', 'my_func': <function my_func at 0x000002>}</code>As shown, locals() displays only the variables inside my_func() , whereas globals() displays everything, including the function itself.
Differences Between locals() and globals()
Below are the basic differences:
locals() captures variables created inside a function and returns a dictionary of local variables.
globals() returns a dictionary of all global variables.
How locals() Works Inside a Function
locals() only captures variables created within the function and returns a dictionary of those local variables.
Can We Modify locals() ?
Many think you can change local variables via locals() . Consider this example:
<code>def my_func():
x = 1
locals()['x'] = 999
print(x)
my_func()</code>What does it print? The output is:
<code>1</code>The modification of locals() does not take effect because Python’s handling of function locals is special; the dictionary returned by locals() is not always writable.
Can We Modify globals() ?
Unlike locals() , globals() returns the global variable dictionary, which can be modified to change global values. Example:
<code>x = "global"
def my_func():
global x
y = "local"
globals()['x'] = "modified"
print("Inside function:", x)
my_func()
print("Outside function:", x)</code>Output:
<code>Inside function: modified
Outside function: modified</code>This shows that modifying globals() successfully changes the global variable x .
Practical Use Cases for locals() and globals()
Although they may seem obscure, these functions are powerful in certain scenarios:
Dynamic Variable Names
You can create variables dynamically using globals() :
<code>def create_variables():
for i in range(3):
globals()[f'var_{i}'] = f'value_{i}'
create_variables()
print(var_0, var_1, var_2)</code>Output:
<code>value_0 value_1 value_2</code>Debugging and Logging
Both locals() and globals() can be printed to quickly inspect the current state of a program:
<code>def my_func(a, b):
result = a + b
print("Locals:", locals())
print("Globals:", globals())
my_func(5, 3)</code>Output (excerpt):
<code>Locals: {'a': 5, 'b': 3, 'result': 8}
Globals: {...}</code>Precautions
Code readability : Overusing locals() and globals() can make code harder to understand for developers unfamiliar with these functions.
Performance issues : Frequent calls to these functions may affect performance because they dynamically build and return variable dictionaries.
Scope confusion : Using both inside nested functions can lead to ambiguous scopes.
Summary
locals() and globals() are useful Python tools that allow dynamic access and modification of variables. While they may seem unintuitive at times, proper use can make your code more flexible and powerful.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.