Modules
• Python organizes code into units called modules.
• A group of functions, variables and classes saved to file is called module
• Simply, a module is a (.py) file consisting of Python code.
• A module has its own namespace (meaning that the names of variables, functions,
and other Python objects are unique to that module and do not overwrite the names in
other modules) and can contain arbitrary Python code.
• we can access the code in a module by importing the module by using a keyword
import followed by a module_name if we want to access particular attribute then
modulename.attribute
• Python has numerous built-in modules (math,date,sys…). You can find an
exhaustive list of these built-in modules in the Python Library Reference.
• We can also write our own modules. In fact, every Python file is its own
module.
Importing Modules
• The process of associating attributes from other modules with your module is
called importing.
• mymath module contains three attributes (members) one variable and 2 functions.
• If we want to use members of module in our program then we should import that
module.
Syntax: import modulename
• We can access members by using module name.
modulename.variable
modulename.function()
Eg: mymath.py
x=599
def add(a,b):
print("The Sum:",a+b)
def product(a,b):
print("The Product:",a*b)
Accessing Attributes of a Module
Python allows a module the ability to "bring in" and use attributes from other modules to take
advantage of work that has been done, maximizing code reusability.
import mymath
print(mymath.x)
mymath.add(10,20)
mymath.product(10,20)
Output
888
The Sum: 30
The Product: 200
Python provides inbuilt function dir() to list out all members of current module or a specified module
dir(module_name).
Note: Whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently.
Renaming a module
Renaming a module at the time of import (module aliasing):
Eg:
import mymath as m
here mymath is original module name and m is alias name.
We can access members by using alias name m
Eg:
import mymath as m
print(m.x)
m.add(10,20)
m.product(10,20)
The from-import Statement
We can import particular members of module by using “from import”.
The main advantage of this is we can access members directly without using
module name.
Eg:
from mymath import x,add
print(x)
add(10,20)
product(10,20)==> NameError: name 'product' is not defined
We can import all members of a module as follows
from mymath import *
Various Possibilities of import
Various Possibilities of writing import statement
1. import modulename
2. import module1,module2,module3
3. import module1 as m
4. import module1 as m1,module2 as m2,module3
5. from module import member (importing attribute)
6. from module import member1,member2,memebr3 (Multiline import)
7. from module import memeber1 as x (Extended Import Statement (as))
8. from module import *
Modules and Files
• If modules represent a logical way to organize your Python code, then files
are a way to physically organize modules.
• To that end, each file is considered an individual module, and vice versa.
• The filename of a module is the module name appended with the (.py) file
extension.
Module Namespaces
• namespace is an individual set of mappings from variable(keys) to objects(objects).
• module names play an important part in the naming of their attributes. The name of
the attribute is always prepended with the module name.
• For example, the factorial() function in the math module is called math.factorial().
Because
• only one module with a given name can be loaded into the Python interpreter, there
should be no intersection of names from different modules.
• If I created a function called factorial() in my own module, perhaps mymodule, its
name would be mymodule.factorial().
• So even if there is a name conflict for an attribute, the fully qualified namereferring
to an object via dotted attribute notation prevents an exact and conflicting match.
Reloading a Module
A module is loaded only once, regardless of the number of times it is imported. This prevents the
module "execution" from happening over and over again if multiple imports occur.
module1.py
print("This is from module1")
Test.py
import module1
import module1
import module1
print("This is test module")
Output
This is from module1
This is test module
The problem in this approach is after loading a module if it is updated outside then updated version of
module1 is not available to our program.
Module Built-in Functions
1.reload(): We can solve this problem by reloading module explicitly based
on our requirement.
We can reload by using reload() function of importlib module.
Syntax: reload(module)
import importlib
importlib.reload(module1)
import time
import module1 from imp import reload
import module1 import module1
from importlib import reload time.sleep(30)
reload(module1) reload(module1)
reload(module1)
time.sleep(30)
reload(module1)
reload(module1)
print(“Main file")
print("This is test module")
The main advantage of explicit module reloading is we can ensure that
updated version is always available to our program.
Module Built-in Functions
3.global() and local() functions:
The globals() and locals() functions can be used to return the names in the
global and local namespaces depending on the location from where they
are called.
• If locals() is called from within a function, it will return all the names that
can be accessed locally from that function.
• If globals() is called from within a function, it will return all the names
that can be accessed globally from that function.
• The return type of both these functions is dictionary. Therefore, names can
be extracted using the keys() function.
Math Module
It is a module that contains several functions to perform
mathematical operation.
If we want to use this module then we have to import it first.
from math import *
Math Functions
• floor(n) – Decrease n value to the previous integer value . If n is integer,
then same value is returned.
• ceil(n) – Raise n value to the next higher integer. If n is integer, then same
value is returned.
• fabs(n) – Returns absolute value or positive quantity of n
• factorial(n) – Returns factorial value of n
• sqrt(n) – Returns positive square root of n
• pow(n,m) – Returns n value to the power of m
Math Functions
• sin(n) – Returns the sine of n
• cos(n) – Returns the cosine of n
• tan(n) – Returns the tangent of n
• gcd(n, m) - Return the greatest common divisor of the integers a and b. If
either a or b is nonzero, then the value of gcd(a, b) is the largest positive
integer that divides both a and b. gcd(0, 0) returns 0.
https://docs.python.org/3/library/math.html
Datetime Module
• The Python datetime module is a relatively complex module that simplifies operations on
dates and times.
• It provide predefined variables and functions to represent date and time in Python
applications.
• In datetime module there are mainly five objects.
1. date
2. time
3. datetime
4. timedelta
5. Timezone
import datetime
date1 = datetime.date(2016, 1, 7)
print(date1)
print(date1.year)
print(date1.month)
print(date1.day)
Random Module
• This module defines several functions to generate random numbers. We can use these
functions while developing games, in cryptography and to generate random numbers on fly
for authentication.
1.Random() function
This function always generate some float value between 0 and 1 ( not inclusive) 0<x<1
Eg:
from random import *
for I in range(10):
print(random())
Random Module
2. randint() function:
To generate random integer beween two given numbers(inclusive)
Eg:
from random import *
for i in range(10):
print(randint(1,100))
3.uniform():
It returns random float values between 2 given numbers(not inclusive)
Eg:
from random import *
for i in range(10):
print(uniform(1,10))