A9. Python Namespace and Scope
Let's begin this tutorial by understanding the meaning of variable, and dive deep into namespace in python.
In programming, a variable is a symbolic name or identifier used to represent the value of a data object or entity. Variables are used to store values and associate them with a descriptive name.
Using variables has some key benefits:
- It allows you to use descriptive names to refer to the values, which makes code more readable and understandable.
- You can reuse variable names for different values in separate parts of your code without conflict or confusion, as long as they have separate scopes.
- The variable name can remain the same even if the value it represents changes, which allows updating values easily.
In Python, a namespace is a mapping of names to objects. It is a dictionary that contains the names defined in a particular scope and the objects associated with those names.
Namespaces are used to avoid naming conflicts and to organize code into logical groups.
There are four types of namespaces in Python:
1. Built-in namespace : This namespace contains the built-in functions, modules, and exceptions that are part of the Python language. They are always available and do not need to be imported.
2. Global namespace : This namespace contains the names defined at the top level of a module. They are visible throughout the module and can be accessed from any function or class within the module.
3. Local namespace : This namespace contains the names defined within a function or class. They are visible only within that function or class and are destroyed when the function or class is exited.
4. Non-local namespace : This namespace contains the names defined in an enclosing function. They are visible to nested functions and are used to implement closures.
The scope of a name is the region of the program where that name is visible. In Python, there are three types of scopes:
1. Local scope : This scope is created when a function or method is called. It contains the names defined within that function or method.
2. Enclosing scope : This scope is created when a function or method is defined inside another function or method. It contains the names defined in the enclosing function or method.
3. Global scope : This scope is created when a module is imported or when a script is executed. It contains the names defined at the top level of the module or script.
The scope of a name determines where that name can be accessed in the program. Names defined in a local scope are not visible outside of that scope, while names defined in a global or enclosing scope can be accessed from within a local scope.
Python Variable Scope
The concept of scope determines which variables can be accessed from which areas of a program.
Scope refers to the portion of a program from which a namespace can be directly accessed without a prefix. There are typically three nested scopes:
- The local scope of the current function, which contains local variables
- The global scope of the module, which contains global variables
- The outermost built-in scope, which contains built-in names
When you reference a name in your code, Python searches for it in the innermost scope first and then moves outwards. So within a function, a local variable will be found before a global variable of the same name.
Nested functions also have nested scopes, so the local scope of the inner function is searched first, then the local scope of outer functions, and so on.
Example for Built-in NameSpace
Let’s check out an example for built-in namespace.
my_list = [1, 2, 3]
In this example, list
is a built-in type in Python and is therefore part of the built-in namespace. We use this built-in type to create a new list object my_list
, which we can then manipulate and use in our program.
For instance, consider the following code:
>>> len(my_list)
3
>>> my_list.append(4)
>>> my_list
[1, 2, 3, 4]
In this example, we use the built-in len()
function to get the length of my_list
, which is 3
. We then use the built-in append()
method to add the value 4
to my_list
, which modifies the list in place. These built-in functions and methods are part of the built-in namespace and are always available in Python without having to be imported or defined in our code.
Example for Global NameSpace
Let’s check out an example for global namespace:
my_var = 10
def my_func():
do_something...
print(my_var)
In this example, my_var
is a name defined at the top level of the module, and therefore it belongs to the global namespace. This name can be accessed from any function or class within the module without having to be explicitly passed as an argument or imported using the import
statement.
For instance, consider the following function:
def my_func():
print(my_var)
This function can access the global variable my_var
without having to pass it as an argument:
>>> my_func()
10
Because my_var
is defined in the global namespace, it is visible to the my_func()
function and can be accessed from within the function’s local scope.
Example for Local NameSpace
Here’s an example of a name in a local namespace:
def my_func():
my_var = 10
print(my_var)
In this example, my_var
is a name defined within the my_func()
function, and therefore it belongs to the local namespace of the function. This name is only visible within the function and cannot be accessed from outside of the function.
For instance, consider the following code:
>>> my_func()
10
>>> print(my_var)
NameError: name 'my_var' is not defined
In this example, when we call the my_func()
function, the name my_var
is defined in the local namespace of the function and is set to the value 10
. When we try to access my_var
outside of the function, we get a NameError
because it is not defined in the global namespace.
This demonstrates that names defined in a local namespace are only accessible within the function or method in which they are defined, and are destroyed when the function or method exits.
Global Keyword in Python
the global
keyword is used to indicate that a variable is a global variable, meaning that it is defined in the global namespace and can be accessed and modified from anywhere in the program.
When a variable is defined inside a function or method, it is by default a local variable, meaning that it is only accessible within the scope of that function or method. However, by using the global
keyword, we can indicate that a variable should be treated as a global variable, even if it is defined inside a function or method.
Here’s an example of how to use the global
keyword in Python:
x = 10
def my_func():
global x
x = 5
print(x)
my_func() # prints 5
print(x) # prints 5
In this example, we define a global variable x
and then define a function my_func()
that modifies the value of x
using the global
keyword. By using the global
keyword, we indicate that x
should be treated as a global variable, even though it is defined inside the function.
When we call my_func()
, it modifies the value of x
to 5
and prints it to the console. When we then print the value of x
outside of the function, we get 5
, because the value of the global variable x
has been modified by the function.
Note that the use of global variables can make it harder to understand and debug code, and can lead to naming conflicts and other issues.
It is generally recommended to use global variables sparingly and to prefer passing arguments and returning values explicitly.