Python Programming UNIT-IV
Modules: Modules and Files, Namespaces, Importing Modules, Importing Module Attributes,
Module Built-in Functions, Packages and Other Features of Modules.
1. Name spaces:
Python namespaces, the structures used to organize the symbolic names assigned to
objects in a Python program.
A namespace is a collection of names.
A namespace is a way of providing the unique name for each object in Python.
Everything in Python is an object, i.e., a variable or a method.
An assignment statement creates a symbolic name that you can use to reference an object.
The statement sai= ‘str' creates a symbolic name sai that refers to the string object ‘str'.
In a program of any complexity, you’ll create hundreds or thousands of such names, each
pointing to a specific object. How does Python keep track of all these names so that they
don’t interfere with one another?
We are going to study:
How Python organizes symbolic names and objects in namespaces
When Python creates a new namespace
How namespaces are implemented
A namespace is a collection of currently defined symbolic names along with information
about the object that each name references.
A namespace as a dictionary in which the keys are the object names and the values are
the objects themselves.
Each key-value pair maps a name to its corresponding object. In a Python program, there
are four types of namespaces:
i. Built-In Namespace
ii. Global Namespace
iii. Enclosing Namespace
iv. Local Namespace
These have differing lifetimes. As Python executes a program, it creates namespaces as
necessary and deletes them when they’re no longer needed.
1 [Link],CSD dept,Aitam
Python Programming UNIT-IV
i. The Built-In Namespace:
The built-in namespace contains the names of all of Python’s built-in objects. These are
available at all times when Python is running.
You can list the objects in the built-in namespace with the following command:
Syntax
>>> dir(_builtins_)
The Python interpreter creates the built-in namespace when it starts up.
This namespace remains in existence until the interpreter terminates.
ii. Global Namespace:
The global namespace contains any names defined at the level of the main program.
Python creates the global namespace when the main program body starts, and it remains
in existence until the interpreter terminates.
Strictly speaking, this may not be the only one global namespace.
The interpreter also creates a global namespace for any module that your program loads
with the import statement.
iii. Local and Enclosing Namespaces:
The interpreter creates a new namespace whenever a function executes. That namespace
is local to the function and remains in existence until the function terminates.
def aitam():
print('I am aitam')
def eee():
print(‘I am eee')
return
eee()
print('I am going from aitam')
return
aitam()
2 [Link],CSD dept,Aitam
Python Programming UNIT-IV
In the above example, the function eee() is defined within the body of aitam().
Inside the aitam() we called the eee().
Let's understand the working of the above function –
When we calls aitam(), Python creates a new namespace for aitam().
Similarly, the aitam() calls eee(), eee() gets its own separate namespace.
Here the eee() is a local namespace created for aitam() is the enclosing namespace.
Each of these namespace is terminated when the function is terminated.
2. Modules in Python:
Modules are simply files with the “.py” extension containing Python code that can be
imported inside another Python Program.
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for example: sai . py, is called a module, and its module
name would be sai.
2.1 How to create modules in python:
To create a module, we have to save the code that we wish in a file with the file extension
“.py”. Then, the name of the Python file becomes the name of the module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific
module.
Example
In this example, we will create a module named as [Link] which contains a
function display( ) that contains a code to print some message on the screen.
[Link]
def display(name):
print("Hi "+name)
3 [Link],CSD dept,Aitam
Python Programming UNIT-IV
2.2 How to use Python Modules:
We need to load the module in another python code to use its functionality.
Python provides two types of statements as defined below.
i. The import statement
ii. The from-import statement
i. The import statement:
The import statement is used to import all the functionality of one module into another.
Here, we must notice that we can use the functionality of any python source file by
importing that file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded
once regardless of the number of times, it has been imported into our file.
The syntax to use the import statement is given below.
Syntax-1
import module_name
Syntax-2
import module1,module2,........ module n
Note: When we are using a function from a module, then we use the following syntax to access
the module:
Syntax
module_name.function_name
Hence, if we need to call the function display() defined in the file [Link], we have to
import that file as a module into our new python program as shown in the example:
Example
import eee
4 [Link],CSD dept,Aitam
Python Programming UNIT-IV
name = input("Enter the name:")
[Link](name)
Output
Enter the name: John
Hi John
ii. The from-import statement:
Instead of importing the whole module into the namespace, python provides the
flexibility to import only the specific attributes of a module.
This can be done by using “from-import” statement.
The syntax to use the “from-import” statement is:
Syntax-1
from module-name import function_name
Syntax-2
from module-name import function 1 , function 2.., function n
Consider the following module named as eee which contains three functions as sum, mul
and div
[Link]
def sum(a,b):
return a+b
def mul(a,b):
return a*b;
def div(a,b):
return a/b;
5 [Link],CSD dept,Aitam
Python Programming UNIT-IV
[Link]
from eee import sum
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print(“Result is: ",sum(a,b))
NOTE: Here we have to note that when we try to import using the from keyword, then do not
use the module name when referring to elements in the module.
2.3 Variables in Python Modules:
The module can contain functions, as already described, but can also contain variables of
all types such as arrays, dictionaries, objects, etc.
[Link]
d = {"name": "John", "age": 26,"country": “India"}
Import the module named mymodule, and access the person1 dictionary:
import EEE
a = EEE.d["age"]
print(a)
2.4 How to rename a Python Module:
We can name the file of the module whatever you like, but we have to note that it must
have the file extension “.py”.
To rename the module name, we can create an alias when you import a module, with the
help of the “as” keyword.
The syntax to rename a module is :
6 [Link],CSD dept,Aitam
Python Programming UNIT-IV
Syntax
import module_name as new_name
[Link]
def sum(a,b):
return a+b
[Link]
import eee as e
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
res = [Link](a,b)
print(“Result is: ",res)
2.5 Advantages of Modules:
i. Reusability: Working with modules makes the code reusable.
ii. Simplicity : The module focuses on a small proportion of the problem, rather than
focusing on the entire problem.
iii. Scoping: A separate namespace is defined by a module that helps to avoid collisions
between identifiers.
2.6. Python Built-in Modules:
As we know that the Python interactive shell has a number of built- in functions.
As a shell start, these functions are loaded automatically and are always available, such
as,print() and input() for I/O,Number conversion functions such as int(), float(),
complex(),Data type conversions such as list(), tuple(), set(), etc.
In addition to these many built-in functions, there are also a large number of pre-defined
functions available as a part of libraries bundled with Python distributions.
These functions are defined in modules which are known as built-in modules.
These built-in modules are written in C language and integrated with the Python shell.
7 [Link],CSD dept,Aitam
Python Programming UNIT-IV
To display a list of all of the available modules in Python Programming Language, we
can use the following command in the Python console:
help('modules')
Built-in modules of Python
i. Math Module
ii. Statistics Module
i. Math Module of Python:
Most popular mathematical functions that are defined in the math module include,
Trigonometric functions
Representation functions
Logarithmic functions
Angle conversion functions, etc.
In addition, two mathematical constants- pi and e are also defined in this module.
In Mathematics, Pi is a well-known mathematical constant. Its value is
3.141592653589793.
>>> import math
>>>[Link]
3.141592653589793
In this example, we will find the value of sin, cos, and tan ratios for the angle of 30
degrees which in radians is equal to 0.5235987755982988 radians.
>>> import math
>>>[Link](0.5235987755982988)
0.49999999999999994
>>>[Link](0.5235987755982988)
0.8660254037844387
>>>[Link](0.5235987755982988)
0.5773502691896257
8 [Link],CSD dept,Aitam
Python Programming UNIT-IV
Many more functions of the math module such as [Link](),
math.log10() [Link]() [Link]() [Link]() [Link]() [Link]() etc.
2.7 Working with Statistics Module of Python:
The statistics module provides functions to mathematical statistics of numeric data. Some
of the popular statistical functions are defined in this module are as follows:
i. Mean
ii. Median
iii. Mode
iv. Standard Deviation
[Link]:
The mean() method returns the arithmetic mean of the numbers present in a list.
>>> import statistics
>>>[Link]([2,5,6,9])
5.5
ii. Median:
The median() method returns the middle value of numeric data present in a list.
>>> import statistics
>>>[Link]([1,2,3,7,8,9])
5.0
>>>[Link]([1,2,3,8,9])
3.0
iii. Mode:
The mode() method returns the most common data point present in the list.
9 [Link],CSD dept,Aitam
Python Programming UNIT-IV
>>> import statistics
>>>[Link]([2,5,3,2,8,3,9,4,2,5,6])
2
iv. Standard Deviation:
The stdev() method returns the standard deviation on a given sample in the form of a list.
For Example,
>>> import statistics
>>>[Link] ([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153
Ex-7a: Write a python program to define a module to find Fibonacci Numbers and import the
module to another program
[Link]
# Fibonacci numbers module
def fib(n):
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
[Link]
import sai
n=int(input(“Enter n value:”))
[Link](n)
10 [Link],CSD dept,Aitam
Python Programming UNIT-IV
Ex-7b: Write a python program to define a module and import a specific function in that module
to another program.
[Link]
def sum(a,b):
return a+b
def mul(a,b):
return a*b;
def div(a,b):
return a/b;
[Link]
from eee import sum
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print(“Result is: ",sum(a,b))
3. Packages:
We organize a large number of files in different folders and subfolders based on some
criteria, so that we can find and manage them easily.
In the same way, a package in Python takes the concept of the modular approach to next
logical level.
As you know, a module can contain multiple objects, such as classes, functions, etc.
A package can contain one or more relevant modules.
Physically, a package is actually a folder containing one or more module files.
A package is basically a directory with Python files and a file with the name init .py.
It's possible to put several modules into a Package.
11 [Link],CSD dept,Aitam
Python Programming UNIT-IV
Let's create a package named mypackage, using the following steps:
i. Create a new folder named D:\MyApp.
ii. Inside MyApp, create a subfolder with the name 'mypackage'.
iii. Create an empty init .py file in the mypackage folder.
iv. Using a Python-aware editor like IDLE, create modules [Link] and
[Link] with the following code:
[Link]
def SayHello(name):
print("Hello ", name)
[Link]
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
12 [Link],CSD dept,Aitam
Python Programming UNIT-IV
3.1 Importing module from a package:
We can import modules from packages using the dot (.) operator.
Import the functions module from the mypackage and call its power() function.
>>>from mypackage import functions
>>>[Link](3,2)
9
def check():
a=int(input('Enter a number'))
if a%2==0:
print("Even")
else:
print("Odd")
>>> import check as check
>>> check()
13 [Link],CSD dept,Aitam