Course contentsShow
← Python
Lesson 168 of 1,0603. Functions and ModularizationFree lesson

Inspecting Namespaces Using Built-in Introspection Tools

You will utilize functions like locals() and globals() to inspect the current state of namespaces and debug variable visibility issues.

In this lesson, you will learn how to peek inside your code’s "storage bins" by using built-in introspection tools to see exactly which variables are available to you at any given moment.

Peeking Under the Hood

In Python, a namespace is essentially a dictionary that keeps track of all the names (variables, functions, etc.) you have defined and where they live. Sometimes, when your code gets complex, it can be hard to track what is currently in scope. Python provides two very helpful functions, locals() and globals(), to let you inspect these namespaces directly.

Using locals() and globals()

The locals() function returns a dictionary containing all the variables defined within the current local scope. If you call it inside a function, you’ll see only the local variables for that function. Conversely, globals() returns a dictionary representing the global namespace of the module.

Check out this example:

def example_function(a, b):
    x = 100
    print("Local namespace:", locals())
    return a + b + x

example_function(5, 5)
print("Global namespace keys:", globals().keys())

When you run this, locals() inside the function will reveal the dictionary {'a': 5, 'b': 5, 'x': 100}. Using globals() at the bottom will show you a much larger list, including all the built-in functions Python provides, plus any variables you defined at the top level of your script.

Debugging with Introspection

These tools are incredibly useful for debugging. If you ever find yourself wondering, "Why is my variable not accessible?" or "Did I accidentally overwrite a global variable?", you can print the contents of these namespaces.

By inspecting the output, you can see if a variable exists where you expect it to be, or if you are accidentally shadowing a global variable with a local one. Remember, these dictionaries are "live"—they update as your program executes—making them perfect for catching bugs related to the LEGB (Local, Enclosing, Global, Built-in) rule.

Key Takeaway: You can use locals() and globals() to return dictionaries of your current variable states, providing a powerful way to debug visibility and scope issues within your Python programs.