In Python, a namespace is a mapping from names to objects. Think of it as a dictionary where the keys are the object names and the values are the objects themselves.
This is wildly useful within code as namespaces avoid having naming conflicts amongst functions, variables, classes, etc. This tutorial will guide you through the process of listing namespaces within Python.
Step 1: Understanding Python Namespaces
All names in Python are not created equal. Depending on where you define a name, that name does not have the same scope or lifetime. These differences in availability are what lead us to distinguish between {link| different types of namespaces |url} in Python. These categories are “Local”, “Global” and “Built-in”.
Step 2: Utilising Python’s dir() function
Python provides a built-in function called dir() that returns a sorted list of names in the current local scope or a list of attribute of an object when you pass an argument to dir(). Without any arguments, dir() will list the names you have defined currently.
1 2 3 4 5 6 7 8 9 |
variable1 = "this is a string" function1 = lambda x : x**2 class ExampleClass: def function_in_class(self): pass dir() |
The output, displays the names defined in the current namespace:
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'ExampleClass', 'function1', 'variable1']
Step 3: Listing the Names in a Namespace
From here, you can gather a list of the names within a certain namespace using Python’s globals() and locals() functions which return a dictionary of the current global and local symbol table.
1 2 3 4 |
global_namespace = sorted(globals().keys()) local_namespace = sorted(locals().keys()) print("Global namespace:", global_namespace) print("Local namespace:", local_namespace) |
Here’s the full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
variable1 = "this is a string" function1 = lambda x : x**2 class ExampleClass: def function_in_class(self): pass print(dir()) global_namespace = sorted(globals().keys()) local_namespace = sorted(locals().keys()) print("Global namespace:", global_namespace) print("Local namespace:", local_namespace) |
Conclusion
Understanding namespaces and their use cases within Python is crucial for managing larger codebases and avoiding naming conflicts.
The ability to list the names within a namespace can often provide useful insights into the code’s workings and improve debugging, eliminating the risk of overwriting or clashing with existing names.
Being well-versed in these features enables programmers to efficiently manage and handle objects in memory in Python.