In Python, a namespace is a mapping from names to objects. Python's namespace is a system designed to ensure the uniqueness of object names and prevent naming conflicts. Namespaces are crucial in Python programming as they help organize and manage various elements in code, such as variables, functions, classes, and modules.
Python namespaces can be categorized into three main types:
-
Local Namespace: This refers to variables defined within a function. When the function executes, the local namespace is created and destroyed upon function completion.
Example:
pythondef my_function(): # This defines a variable in the local namespace local_var = 5 print(local_var) my_function() # Output: 5 -
Global Namespace: This includes all variables, functions, and classes defined in the current module. The global namespace is created when the module is loaded and persists until script execution ends.
Example:
python# Global variables are defined in the global namespace global_var = 10 def access_global_var(): # Accessing a variable from the global namespace print(global_var) access_global_var() # Output: 10 -
Built-in Namespace: This contains Python's built-in functions and exceptions, such as
len(),print(), andException. These elements are created when the Python interpreter starts and are available across all modules.Example:
python# Using functions from the built-in namespace print(len("hello")) # Output: 5
When referencing a name in your code, Python searches for it in the following order:
- First, in the local namespace.
- If not found, then in the global namespace.
- Finally, in the built-in namespace.
If the name is not found in any namespace, a NameError exception is raised. This structured namespace management enhances code clarity and organization while preventing naming conflicts in large projects.