Python Namespace and Scope: In Python, a namespace is a mapping from names to objects. It provides a way to organize and manage names in a program, ensuring that names are unique and do not conflict with each other. Namespaces play a crucial role in determining the scope of variables and other objects.
Scope, on the other hand, defines the visibility and accessibility of names within a program. It determines where a name can be accessed and which part of the program can reference it. Python has several types of scopes, including global scope, local scope, and built-in scope.
Let’s explore the concepts of namespace and scope with an example:
# Global scope
global_var = 10
def my_function():
# Local scope
local_var = 20
print(local_var) # Output: 20
print(global_var) # Output: 10
my_function()
print(global_var) # Output: 10
print(local_var) # NameError: name 'local_var' is not defined
In this example, we have a global variable global_var
defined outside any function. It is accessible from anywhere in the program, including inside functions. Within the my_function()
function, we define a local variable local_var
, which is only accessible within the function’s local scope. When we print local_var
within the function, it successfully displays the value of 20
. However, when we try to access local_var
outside the function, we get a NameError
because it is not defined in the global scope.
Each function in Python has its own local scope, which is created when the function is called and destroyed when the function finishes executing. Names defined within a function are part of its local namespace and are not accessible outside the function. Similarly, variables defined in the global scope are part of the global namespace and can be accessed throughout the program.
Python also has a built-in namespace that contains pre-defined names like built-in functions and modules, such as print()
and math
. These names are always accessible without explicitly importing or defining them.
Understanding namespaces and scopes is essential for managing variable names and avoiding naming conflicts. By organizing names into separate namespaces with different scopes, we can maintain clarity and control over our program’s variables and objects.