Python3 Modules
CS-UH 1001, Fall 2022
Alex Delis
NYU-Abu Dhabi
October 2022
Modules
We have worked with an number of modules including random, time and os.
Module functions that we have used so far:
– [Link](1,5) to generate random numbers between 1 and 5.
– [Link](2) to pause a program in execution for 2 secs.
– [Link]("clear") to clear the screen of a tty.
1
Modules
A module is a set of functions that can be used by programmers.
– To use a module-function, the module of interest has to be first imported into the
program.
– This is done simply by the statement: import ModuleName
– The import statement should be added at the top of the program.
– Once a module has appeared on a program, its functions are available and can be
invoked.
2
Selective Importation of Functions
We can selectively input a specific function out of a module.
Syntax:
– from moduleName import functionName
Example:
# Bring in just the 1 function: randint 1
from random import randint 2
3
## randint can be used without any further qualification 4
mynum=randint(1,6) 5
3
The math Module
The math Module features numerous useful math-routines.
math functions include:
– sqrt(x) returns the square root of a number
– exp(x) returns ex
– log(x) returns the natural logarithm of x
– log10(x) returns the base-10 logarithm of x
– sin(x) returns the sine of x
– cos(x) returns the cosine of x
Description of math at: [Link]
Description of random at: [Link]
Description of os at: [Link]
4
Functions & Modules
A module is simply a file that contains functions:
– You can create your own module to break a large(r) program into more manageable
pieces of work or functions.
– This is the idea of modularity; writing manageable pieces of code at a time that
display cohesion.
– In this way, one can reuse code rather that working towards new code every time
there is a need.
Gold Rule in Computing: it is better/easier to deal with a number of smaller problems
than a large one!
– “Divide and Conquer”
5
Create a Module
A module can be put together as follows:
– Create a separate .py file that will contain the code for the module.
– The name of the file will be the name of the module.
– In the module, you can define any functions you may desire.
– You can import the module and use its functions.
The module can be in the same File-System directory as your program (to make matters
easy).
6
Ways to import Modules and their Functions
There is some flexibility when import-ing modules and their functions:
Approach 1: Full Function Identification
import math 1
2
alpha = [Link](10) 3
beta = [Link]*[Link](1.018) 4
print("alpa is: ",alpha," beta is: ",beta) 5
Approach 2: Using a (shorter) Handle
import math as h 1
2
alpha = [Link](10) 3
beta = [Link] * [Link](1.018) 4
print("alpa is: ",alpha," beta is: ",beta) 5
7
Ways to import Modules and their Functions
Approach 3: Selective Identification of Functions
from math import sqrt, pi, cos # syntax changes a bit 1
2
alpha = sqrt(10) # math is not named here! 3
beta = pi * cos(1.018) 4
print("alpa is: ",alpha," beta is: ",beta) 5
Approach 4: Full Inclusion of all Functions
from math import * # syntax changes a bit 1
2
alpha = sqrt(10) # math is not named here! 3
beta = pi * cos(1.018) 4
print("alpa is: ",alpha," beta is: ",beta) 5
8
The circle Module
Create a circle module that features 3 functions that compute:
– the area of a circle.
– the perimeter (circumference) of a circle.
– the diameter of a circle.
All functions have as input the radius r of a circle.
We edit a .py file names [Link] and in this file we provide the implementation of
the 3 above functions.
9
The [Link] Module
import math 1
2
def diameter(radius): 3
""" Function computes the Diameter 4
Parameter: radious of circle - outcome in float 5
""" 6
return (float(2*radius)) 7
8
def perimeter(radius): 9
""" Function computes the Circumference 10
Parameter: radious of circle - outcome in float 11
""" 12
return(float(2*[Link]*radius)) 13
14
def area (radius): 15
"""This function is used to calculate the area of a circle. 16
Parameter: radious of circle - Outcome in float 17
""" 18
return (float([Link]*radius**2)) 19
10
Working with the circle Module
A sample session of working with circle
>>> import circle 1
>>> print([Link](4)) 2
25.132741228718345 3
>>> 4
>>> print([Link](3)) 5
6.0 6
>>> 7
>>> print([Link](23)) 8
1661.9025137490005 9
>>> 10
11
Using the time Module
Measuring the amount of time expended on executing a function or even some lines of
code is occasionally of paramount importance to understand the behavior of a program.
– The time module helps in providing timing & performance measurements.
import time as t 1
2
def CarryAddition(inrange): # Add all numbers in a provided range 3
SumNum = 0 4
for i in inrange: 5
SumNum += i 6
return SumNum 7
8
addNumsUpto = 1500000 9
testdata = range(addNumsUpto) 10
11
MyTime1 = t.perf_counter() # start timing 12
TheResult = CarryAddition(testdata) # the work of CarryAddition gets timed 13
MyTime2 = t.perf_counter() # stop timing 14
print("My TheResult is {0}\ 15
(time taken = {1:.4f} secs)".format(TheResult, MyTime2-MyTime1)) 16
17
MyTime3 = t.perf_counter() # start timing 18
sumResult = sum(testdata) # the work of Python3 sum gets timed 19
MyTime4 = t.perf_counter() # stop timing 20
print("Python3 sumResult is {0}\ 21
(time taken = {1:.4f} secs)".format(sumResult, MyTime4-MyTime3)) 22
12
Namespaces
A namespace is a collection of identifiers/objects that belong either to a module or to
a function.
– A namespace is often used to retain related things.
– For example, a namespace may hold all math functions we develop and use.
– Each module has its own namespace.
– The same object/variable name can appear in different modules with no problems.
– Such identically-named objects are not related as they are placed in different
namespaces.
13
Using Identically-named Objects from Different Namespace
Module =⇒ [Link]
# this is definition of [Link] 1
2
FirstName="Dena" 3
LastName="Ahmed" 4
Module =⇒ [Link]
# this is defintion of [Link] 1
2
FirstName="Alex" 3
LastName="Delis" 4
Handling identically-named objects FirstName and LastName defined in both
modules in [Link] program:
import moduleAD as ad 1
import moduleDA as da 2
3
''' 4
FirstName in moduleAD module is distinct from 5
FirstName in moduleDA 6
''' 7
print("What is your first name? ", [Link],) 8
print("What is your first name? ", [Link]) 9
print("What is your last name? ", [Link],) 10
print("What is your last name? ", [Link]) 11
14
Namespace and Functions
Do not forget: every function maintains its own namespaces or scope or
“realm-of-activity” for its locally defined objects.
def foo(): 1
## foo()'s block is the namespace in which object 2
MyVar = 444 3
MyVar += 1 # is active 4
print("val of MyVar inside of foo():", MyVar) 5
6
def bar(): 7
# bar()'s block is the namespace in which object 8
MyVar = 333 # is active 9
print("val of MyVar inside of bar():", MyVar) 10
11
# the MyVar object below is active in the namespace of 12
MyVar = 111 # the main block of istructions. 13
print("val of MyVar before calling foo():", MyVar) 14
foo() 15
print("val of MyVar after calling foo():", MyVar) 16
bar() 17
print("val of MyVar after calling bar():", MyVar) 18
15
Namespaces and Functions
The execution:
ad@andros:~/src-009$ python3 [Link] 1
val of MyVar before calling foo(): 111 2
val of MyVar inside of foo(): 222 3
val of MyVar after calling foo(): 111 4
val of MyVar inside of bar(): 333 5
val of MyVar after calling bar(): 111 6
ad@andros:~/src-009$ 7
Here, we have 3 instances of objects named MyVar that operate off different
namespaces or scopes.
– These 3 instances of MyVar do not present any conflict among themselves and there
is no apparent collision in their work as they are “fitted” (i.e., are applicable) in
different scopes.
– Metaphor =⇒ You have 3 campus professors named “Asma”: these are all different
individuals (i.e., “instances” of persons..) who likely have nothing to do with each
16 other!
The Relationship Among: Namespaces, Modules, Files & Dirs
A few points to remember:
Files and Directories organize data/information in a computer system:
– files and directories often featuring easily-understood-for-users symbolic names, help
the OS find the corresponding Bytes making up their content.
Namespaces and Modules are Python3’s facilities that:
– they help organize how we would like to cluster related functions and
objects/attributes.
– they have nothing to do with where Bytes of information get actually stored.
– the latter is the responsibility of the File-System which undertakes the task to
maintain for us the “content” or Bytes of all files and directories we use.
17
Mini-Task
Create a module termed [Link] that calculates the area, the diagonal as well as
the perimeter of a square.
– area is a2 where a is the length of side.
– diagonal which can be easily derived form a.
– length of perimeter is 4 ∗ a.
18
Alex Delis, [Link] -AT+ [Link]
NYU Abu Dhabi