Dynamic Variables and Namespaces in Python with globals() and locals()
Dynamic Variables and Namespaces in Python with globals() and locals() ๐ง
Python's globals() and locals() functions allow you to inspect and manipulate the namespace at runtime.
They are useful for dynamic variable creation, debugging, or building metaprogramming tools.
✅ Creating Dynamic Variables with globals()
Use globals() to define variables dynamically in the global scope.
# Creating variables dynamically using globals()
for i in range(3):
globals()[f"var_{i}"] = i * 10
print(var_0) # 0
print(var_1) # 10
print(var_2) # 20
✅ Inspecting Local Variables with locals()
locals() gives you access to local variables within a function, returned as a dictionary.
# Using locals() to inspect local variables inside a function
def demo():
a = 10
b = 20
print(locals())
demo()
# Output: {'a': 10, 'b': 20}
✅ globals() vs locals()
Understand the difference in context between global and local namespaces.
# Comparing globals() and locals()
x = 100
def test():
y = 200
print("globals:", 'x' in globals()) # True
print("locals:", 'y' in locals()) # False (outside of test's context)
test()
globals() returns a dictionary of the current global symbol table,
while locals() returns the local symbol table (usually inside functions).
Use these functions carefully, especially when modifying data dynamically.
Clean code understands its own structure. Mastering namespaces gives you the power to build smarter, more flexible programs. ๐
Icons by Flaticon
Comments
Post a Comment