d11 Lecture
d11 Lecture
Python uses the location of the name assignment or definition to associate it with a scope.
If a variable assigned value in the function, it has a local scope.
If a variable assigned value at the top level and outside all the functions, it has a global scope.
Types of namespace
1. Built-in Namespace It includes functions and exception names that are built-in in
the python.
2. Global Namespace It includes the names from the modules that are imported in
the code. It lasts till the end of program.
3 Local Namespace It includes the names defined in the function. It is created
when the function is called and ends when the value
returned.
Built-in scope
It is a special scope which is created or loaded at script run or opens an interactive session.
This scope contains names such as keywords, functions, exceptions, and other attributes that
are built into Python.
Names in this scope are also available from everywhere in your code.
Built in Scope
Global Scope
Enclosing Scope
Local Scope
Example
#var1 is in the global namespace
var1 = 5
def ABC( ):
# var2 is in the local namespace
var2 = 6
def XYZ( ):
# var3 is in the nested local
# namespace
var3 = 7
In this example, the var1 is declared in the global namespace because it is not enclosed
inside any function. So it is accessible everywhere in the script.
var2 is inside the ABC( ). So, it can be accessed only inside the ABC( ) and outside the
function, it no longer exists.
var3 also has a local scope, the function is nested and we can use var3 only inside XYZ(
).
Modules
A module helps to break the large program to manageable and organized code. It allows
the reusability of code.
Module is a Python file containing a set of Python Statements and Functions.
Module files has the “.py” extension. e.g. my_abc.py
Create Module
To create a module , save a file with extension “.py”
File my_abc.py
Import Module
Import Statement help to provide the Module contents to the caller program code.
Import module created a separate namespace, which contains all the objects define in the
module.
Module content like identifiers , functions , class or objects defined in the module can be
accessed using the dot notation like <ModuleName>.<FunctionName>. eg. my_abc.show( )
Syntax
import Module_Name
Example
To import the module “my_abc.py” for using in the “m1.py” program file.
import my_abc
print("\n Accessing function from Module\n")
my_abc.show("vikas",27)
Output
Accessing function from Module
Name : vikas
Age : 27
Renaming Module
To import the module “my_abc.py” and rename it “m” for using in the “m1.py” program file.
import my_abc as m
import my_abc
x=dir( my_abc )
print( x )
print( __file__ )
print( __name__ )
Output
['Employee', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'show']
C:/Python38-32/m2.py
__main__
In this, Employee and show is defined in the “my_abc” module and remaining are the
system defined.
Example-1
from my_abc import show
print("\n Accessing function from Module\n")
show("vikas", 27)
print("\n Accessing Variable from Module\n")
print(Employee["name"]) # This is not accessible, as not imported.
Output
Accessing function from Module
Name : vikas
Age : 27
Accessing Variable from Module
Example-2
Output
Accessing Variable from Module
Ajay
30
20000
Example
from my_abc import *
Output
Accessing Variable from Module
Ajay
30
20000
Name : vikas
Age : 27
Packages
A package is a well-organized hierarchy of sub-directories and files, for easier access of
modules.
The directory is a package [or sub package] and files are modules.
Package is a place for similar modules, and help in grouping and organizing them.
Package directory or sub-directory must contain a file “_ _init__.py” used as initialization
code. It can be an empty file. However, it new version of python, this is not compulsory.
Packages help avoid collisions between module names and modules help avoid collision
between variable names.
Packages are helpful to manage the large projects having lots of modules.
Create Package
To create a Package – MyPkg perform the following steps –
1) Create a folder on “D:\MyPkg”
2) Create a sub folder in D:\MyPkg – P1 & P2
Module M1.py
Employee={ "name":"Ajay M1", "age":27, "salary":30000}
def show(name):
print("Name :", name)
Module M2.py
Employee={ "name":"Vijay M2", "age":27, "salary":30000}
def sum(x , y):
return(x+y)
Module M3.py
def show(name, age):
print("Name :", name)
print("Age :", age)
Employee={ "name":"Ajay M3", "age":27, "salary":30000}
Module M4.py
def mul(x,y):
print("sum : ", x*y)
Import Package
Import Statement help to provide the Module contents to the caller program code.
Import Package creates a separate namespace for each sub package, which contains all the
objects define in the module.
We can provide the path for package using sys.path.append("Package Path") in the code or
modify the PYTHONPATH environment variable.
Package content like identifiers, functions, class or objects defined in the module can be
accessed using the dot notation like <PackageName>.<ModuleName>.<FunctionName>.
eg. MyPkg.my_abc.show( )
Syntax
import Package_Name.Module_Name
Example
To import the package “D:\Mykg\P1” for using in the “m1.py” and “m2.py” module file.
import sys
sys.path.append("D:\\")
import MyPkg.P1.m1
import MyPkg.P1.m2
Output
Objects in P1 - m1 module
['Employee', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'show']
Objects in P1 - m2 module
['Employee', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'sum']
Accessing P1 - m1 module
Name : Ajay
Accessing P1 - m1 module
Ajay M1
Accessing P1 - m2 module
Sum : 40
Accessing P1 - m2 module
Vijay M2
Renaming Module
To import the package “D:\Mykg\P1\m1” and rename it as“M1” for using in the program file.
import sys
sys.path.append("D:\\")
import MyPkg.P1.m1 as M1
import MyPkg.P1.m2 as M2
Output
Accessing P1 - m1 module
Name : Ajay
Accessing P1 - m1 module
Ajay M1
Accessing P1 - m2 module
Sum : 40
Accessing P1 - m2 module
Vijay M2
Output
Objects in P1 - m1 module
['Employee', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'show']
D:\MyPkg\P1\m1.py
MyPkg.P1.m1
Objects in P1 - m2 module
['Employee', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'sum']
D:\MyPkg\P1\m2.py
MyPkg.P1.m2
In this, Employee and show is defined in the “m1” module and
Employee and sum is defined in the “m2” module and
Remaining is the system defined.
Packages
Module m1.py
Employee={ "name":"Ajay M1", "age":27, "salary":30000}
def show(name):
print("Name :", name)
Module m2.py
Employee={ "name":"Vijay
me":"Vijay M2", "age":27, "salary":30000}
def sum(x,y):
return(x+y)
Module m3.py
def show(name,age):
print("Name :", name)
print("Age :", age)
Employee={ "name":"Ajay M3", "age":27, "salary":30000}
Module m4.py
def mul(x,y):
print("sum : ", x*y)
Example-1
import sys
sys.path.append("D:\\")
Output
Accessing P1 - m1 module
Name : Ajay
Accessing P1 - m2 module
Sum : 40
Accessing P1 - m1 module
Traceback (most recent call last):
File "D:\Python38\p3.py", line 17, in <module>
print( Employee["name"])
NameError: name 'Employee' is not defined
Example-2
import sys
sys.path.append("D:\\")
Output
Objects loaded in Memory
['Employee', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'sys']
Accessing P1 - m1 module
Vijay M2
Accessing P1 - m2 module
Vijay M2
In this, Employee object is present in both the modules (m1 and m2), so the Employee object
from the module-m2 replaces Employee from the module-m1. Thus, output is same in above
case. To resolve this issue, follow the following example
Example-3
import sys
sys.path.append("D:\\")
Output
Objects loaded in Memory
['E1', 'E2', '__annotations__', '__builtins__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'sys']
Accessing P1 - m1 module
Ajay M1
Accessing P1 - m2 module
Vijay M2
Example-1
import sys
sys.path.append("D:\\")
from MyPkg.P1 import *
print("Objects loaded in Memory")
print(dir())
print("Accessing P1 - m1 module ")
print( m1.Employee["name"])
Output
Objects loaded in Memory
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'm1', 'm2', 'sys']
Accessing P1 - m1 module
Ajay M1
Accessing P1 - m2 module
Vijay M2
Example-2
#__init__.py file not present in D:\MyPkg\P2 folder
import sys
sys.path.append("D:\\")
Output
Accessing P1 - m1 module
Traceback (most recent call last):
File "D:/Python38/p4.py", line 12, in <module>
print( m3.Employee["name"])
NameError: name 'm3' is not defined