NAME SPACES
To understand the Namespace in the program
Name space-Introduction
To simply put it, a namespace is a collection of
names.
In Python, we can imagine a namespace as a
mapping of every name we have defined to
corresponding objects.
It is used to store the values of variables and other
objects in the program, and to associate them with
a specific name.
This allows us to use the same name for different
variables or objects in different parts of your code,
without causing any conflicts or confusion.
Types of Python namespace
Types of Python namespace
A namespace containing all the built-in names is created when we start the Python interpreter and exists as
long as the interpreter runs.
This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the
program. Each module creates its own global namespace.
These different namespaces are isolated. Hence, the same name that may exist in different modules does not
collide.
Modules can have various functions and classes. A local namespace is created when a function is called,
which has all the names defined in it.
Similar is the case with class. The following diagram may help to clarify this concept.
Python Variable Scope
Although there are various unique namespaces defined, we
may not be able to access all of them from every part of the
program. The concept of scope comes into play.
A scope is the portion of a program from where a
namespace can be accessed directly without any prefix.
At any given moment, there are at least three nested scopes.
Scope of the current function which has local names
Scope of the module which has global names
Outermost scope which has built-in names
Scope and Namespace in Python
# global_var is in the global namespace
global_var = 10
def outer_function():
# outer_var is in the local namespace
outer_var = 20
def inner_function():
# inner_var is in the nested local namespace
inner_var = 30
print(inner_var)
print(outer_var)
inner_function()
# print the value of the global variable
print(global_var)
# call the outer function and print local and nested local variables
outer_function()
Output
10
20
30
Explanation
In the above example, there are three separate namespaces: the
global namespace, the local namespace within the outer function,
and the local namespace within the inner function.
Here,
global_var - is in the global namespace with value 10
outer_val - is in the local namespace of outer_function() with
value 20
inner_val - is in the nested local namespace of inner_function() with
value 30
When the code is executed, the global_var global variable is printed
first, followed by the local variable: outer_var and inner_var when
the outer and inner functions are called.
Use of global Keyword in Python
# define global variable
global_var = 10
def my_function():
# define local variable
local_var = 20
# modify global variable value
global global_var
global_var = 30
# print global variable value
print(global_var)
# call the function and modify the global variable
my_function()
# print the modified value of the global variable
print(global_var)
Output
10
30
Explanation
Here, when the function is called,
the global keyword is used to indicate
that global_var is a global variable, and its
value is modified to 30.
So, when the code is executed, global_var is
printed first with a value of 10, then the
function is called and the global variable is
modified to 30 from the inside of the function.
And finally the modified value of global_var is
printed again.
Introduction to Computing Using Python
Namespaces – Local and Global
The Purpose of Functions
Global versus Local Namespaces
The Program Stack
How Python Evaluates Names
Introduction to Computing Using Python
The purpose of functions
Functions make it easier for us to code solutions to problems. They
provide
• Modularity: They allow us to break down complex problems that
require complex programs into small, simple, self-contained pieces.
Each small piece can be implemented, tested, and debugged
independently.
• Abstraction: A function has a name that should clearly reflects what it
does. That action can then be performed by calling the function by name,
abstracting what the function does from how it does it.
• Code reuse: Code that may be used multiple times should be
packaged in a function. The code only needs to be written once.
And any time that it needs to be modified, extended or debugged,
the changes need to be made only once.
Introduction to Computing Using Python
Local variables hide what goes on inside
a function
Enter this code in pythontutor and trace its execution.
def double(y):
x = 2
y *= x
print('inside double', 'x = ', x, 'y = ', y)
x, y = 3, 4
print('outside double', 'x = ', x, 'y = ', y)
double(y)
print('after double', 'x = ', x, 'y = ', y)
First, x and y are created in the global frame.
While double executes, local x and y are created with their own values.
These local variables cease to exist when the function exits.
Separating what happens inside a function from what happens contributes
to your program's modularity.
Introduction to Computing Using Python
Function namespace
Every execution of a function creates a local
namespace that contains its local variables.
In this example there are multiple values of n,
one in each namespace. How are all the
namespaces managed by Python? Which line
does Python return to?
def g(n):
print('Start g')
n += 1
print('n = ', n)
def f(n):
print('Start f')
n += 1
print('n = ', n)
g(n)
n = 1
print('Outside a function, n = ',n)
f(n)
Introduction to Computing Using Python
Scope and global vs. local namespace
Every function call has its own (local) namespace
• This namespace is where names defined during the
execution of the function (e.g., local variables) live.
• This namespace comes into existence when the
function
is called. It goes out of existence when the function
exits
Every name in a Python program has a scope
(returns).
• This applies to the name of a variable, a function, a class, …
• Outside its scope, the name does not exist. Any reference
to it will result in an error.
• Names created in the interpreter shell or in a module and
outside of any function have global scope.
Introduction to Computing Using Python
Example: variable with local scope
def f(b): # f has global scope, b has local scope
a = 6 # this a has scope local to this call of function f()
return a*b # this a is the local a
a = 0 # this a has global scope
print('f(3) = ', f(3))
print('a = ', a) # global a is still 0
>>> ===RESTART
>>> === RESTART ====
====
>>>
>>>
f(3) = 18
f(3) = 18
a b a a = 0
>>>
shell Function call f(3)
0 3 6
Introduction to Computing Using Python
Example: variable with global scope
deff(b):
def f(b):# f has global
# scope,
f hasb hasglobal
local scope
scope, b has local scope
return
return
a*b # this
a*ba is #
thethis
global aa is the global a
aa ==0 0 # this a has global
# thisscope
a has global scope
print('f(3) = {}'.format(f(3)))
print('f(3) = ', f(3))
print('a is {}'.format(a))
print('a = ', a) # global# a global
is still 0 a is still 0
>>> ===
>>> ===RESTART
RESTART
====
====
>>>
>>>
f(3) = 0= 0
f(3)
a b a = 0
>>>
shell Function call f(3)
0 3
Introduction to Computing Using Python
How Python evaluates names
def f(b): # f has global scope, b has local scope
return a*b # this a is the global a
a = 0 # this a has global scope
print('f(3) = ', f(3))
print('a = ', a) # global a is still 0
printf
When there are duplicate uses of a name,
how does Python decide which instance of
module builtins
the name (e.g., local or global) you are
referring to?
To find the value of a name, Python
f a printf()
searches through namespaces in this
order:
1. First, the local (function) namespace global namespace
0
2. Then the global namespace
3. Finally the namespace of module
b f()
builtins
Function call f(3)
3
Introduction to Computing Using Python
Modifying a global variable inside a function
To modify a global variable from inside a function, use the keyword 'global'.
def f(b):
global a # all references to a in f() are to the global a
a = 6 # global a is changed
return a*b # this a is the global a
a = 0 # this a has global scope
print('f(3) = ', f(3))
print('a = ', a) # global a has been changed to 6
>>> === RESTART ====
a b >>>
f(3) = 18
a = 6
shell Function call f(3) >>>
0 3 6
Assesment
1. Create few name spaces