Namespace in Python and Variable scope.
Namespace in Python and Variable scope.
This tutorial covers a comprehensive guide on namespaces, by the end of the tutorial
you will learn various types of namespaces, and how to access them.
Introduction
Namespace is just like a container. It holds a set of names and links them to the
corresponding objects. These names include variables, functions, classes and or any
other identifier. Namespaces are important because they help us organize and
manage our code by providing a unique space for each identifier thus preventing
conflict in naming.
Types of namespaces
In Python programming language, there are four types of namespaces:
Local namespace
Global Namespace
Built-in Namespace
Enclosing Namespace
a). Local Namespace
These are a set of names that are within a specific function or method. They are
limited to the function and Method in which they have been defined.
Local namespaces are created when a function that has all the names defined
in it is called. The function namespaces stop existing when the function is terminated.
Example
1 #!/usr/bin/python3
2
3 def local_function():
4 """ This function initializes a local variable 'local_var'
5 with a value of 12 and prints it to the console.
6 """
7 local_var = 12
8 print(local_var)
9
10
11 """ Calling the function """
12 local_function()
Output:
12
Local_var is the local namespace used in the local_function above.
b). Enclosing Namespace.
This namespace will be created when a function is defined inside another function.
It has variables from the enclosing(outer) function.
1 #!/usr/bin/python3
2
3
4 def outer_function():
5 """ Outer function
6 defines an outer variable and calls the inner function.
7 """
8 outer_variable = "I am enclosing namespace"
9
10 def inner_function():
11 """ Prints the outer variable from the enclosing namespace.
12 """
13 print(outer_variable)
14
15 inner_function()
16
17
18 """ Calls the outer function """
19 outer_function()
Output:
I am enclosing namespace
c) . Global Namespace.
These are names defined at the top of a module. Individual modules will create their
global namespace. In global namespaces, names of the same nomenclature do not
collide even though they exist in various modules.
1 #!/usr/bin/python3
2 global_var = 20
3
4
5 def global_function():
6 """ This function prints the global variable 'global_var
7 to the console """
8 print(global_var)
9
10
11 """ calling the function """
12 global_function()
Output:
20
In the example ‘global_var’ used in the function above is found in the global
namespace and it is accessed inside the global_function.
d). Built-in Namespace
This namespace has names that have been built into the Python interpreter.
Examples of built-in functions include print(), len(), id() etc. Built-in interpreters are
created whenever Python interpreters are created. The built-in functions are always
available in any part of the program since they always exist whenever the interpreter
runs. Built-in Namespace are globally available and there is no need to import them.
1 #!/usr/bin/python3
2
3 print(len([1, 2, 4, 6]))
Output:
4
In the example above, both print and len are built-in namespaces.
Accessing Namespaces.
A scope is an area or part of the program where we can access the namespaces
directly. Each namespace name will be identical to its scope. We use the scopes
dynamically but define them statically. When a Python program is executed we get
nested scopes. These scopes include:
The innermost scope has all the local names.
Adjacent scope is the enclosing scope that contains the enclosing functions.
The next scope is the module scope containing global names.
The outermost scope has all the built-in names.
I). Locals() Functions
We can use the “locals ()” function to return a dictionary that represents the current
local symbol table, including the local _var in the dictionary.
For example
1 #!/usr/bin/python3
2 def local_function():
3 local_var = 20
4 print(locals())
5
6 local_function()
Output:
{'local_var': 20}
II). Globals () Function
We use the ‘global()’ function to return a dictionary that represents the current
global symbol
table, including the global_var.
III). Built-ins
There is no need for specific calls for built-in namespaces as they are automatically
available.
For example
1 #!/usr/bin/python3
2
3 print(len([4, 6, 8, 10]))
Output:
4
Advanced Concepts
Nested Namespaces.
We can create a hierarchy of scopes by having nested namespaces.
1 #!/usr/bin/python3
2
3 def outer_function():
4 outer_var = 10
5
6 def inner_function():
7 inner_var = 15
8 print(outer_var + inner_var)
9
10 inner_function()
11 outer_function()
Output:
25
In the example above, outer_var is in the outer namespace while inner_var is in the
inner namespace.
Nonlocal declaration
We use the ‘nonlocal’ keyword in assigning values to variables within the nearest
enclosing scope that isn't global.
1 #!/usr/bin/python3
2
3 def outer_function():
4 outer_var = 10
5
6 def inner_function():
7 nonlocal outer_var
8 outer_var = 15
9
10 inner_function()
11 print(outer_var)
12 outer_function()
Output:
15
Variable scope
Variable scope is part of the program in which the variable name is meaningful and
helps the Python interpreter determine which type of variable you were referring to
in your code when the same variable name has been used in several namespaces.
Assume you have a variable name “func” in different namespaces, there is an order
that Python will use to search for “func” in the namespaces available in the code.
This order uses the LEGB rule. Python adheres to this order:
An image showing LEGB process
1. Local: Python will look for the name “func” first in the innermost scope.
2. Enclosing. If the name “func” is not found in the innermost function and there is an
enclosing function, then the Python interpreter will search for it in the scope of the
enclosing function.
3. Global: The Python interpreter will search for the name “func” in this scope if it's
not found in the local and enclosing scopes.
4. Built-in: If the Python interpreter cannot find the name in the three scopes, then
it will search for it in the built-in scope.
This rule is usually referred to as Python literature.
Python will raise a “NameError exception if no name is found in the scopes.
1 #!/usr/bin/python3
2
3 """Demonstrates variable scoping in Python."""
4
5 func = 'global'
6
7
8 def f():
9 """This is the docstring for function f."""
10 func = 'enclosing'
11
12 def g():
13 """This is the docstring for function g."""
14 func = 'local'
15 print(func)
16
17 g()
18
19
20 f()
In the example above, the following lines define various scopes.
Line 5 defines x in the global scope.
Line 10 defines x again in the enclosing scope.
Line 14 defines x a third time in the scope that’s local to g().
Conclusion
This tutorial guide covers the basics and advanced concepts of Python namespaces.
Understanding namespaces is important for writing readable, clean and
maintainable code. Feel free to experiment with the examples provided to deepen
your understanding.
Wow I like the simplicity!
ReplyDelete