Python Modules

A file containing a group of functions, Classes, and Variables that you wanted to include in your applications is called as a Module.

You can also include codes whichever you want and File must be saved with.py extension And Every Python file acts as a Module.

The advantage of python Module is that, once we define any function in a Module and save that Module with the extension .py and you can use this function in any other source file by using the Import statement.

Example :

A file that contains the Addition functionality and product functionality and saved as demo1.py which is nothing but Module.

And I am creating another one module called demo2.py, here I am using the Addition and Product function but instead of defining the function here, I am going to import the same function from the demo1.py Module by using the import keyword.

Module demo.py
a=89
b=29

def add(a,b):
    print("Performing the addition Operation")

print("The sum:",a+b)
    
def product(a,b): 
    print("Performing the multiplication Operation")
   
print("The product:", a*b)

Installation Of Python

Possible ways to Import a Module

There are several inbuilt Modules that are available inside the Python, we can use these Modules in our applications easily by importing the respective Functions.

The syntax to import a module is:

import modulename ##importing module
modulename.variable name ##access the variable after importing the module
modulename.function name() ##To access the any function
Example: Math Module, Random Module, time Module, and threading Module, etc..

Let us see what are the various functions available in the Math Module

import math
print(dir(math))

The output is:

import-math-function

The following example demonstrates how to write a module an how to import that module

First, we need to create a math module/file, we created a math module by the name cherchermath and saved it by using the .py extension

x=888
y=999
def add(a,b):
    print("The sum:",(a+b))
def product(a,b):
    print("The product:",(a*b))
class A:
    pass

Next, we can import the above math module into another program, by creating a new file with the name tester.py. Now you can run the tester.py in the command prompt, it will print the variable values as shown below

import cherchermath
print(cherchermath.x)
print(cherchermath.y)

The output is:

imported-cherchermath-module

And you can also import the add() and product() function

import cherchermath
print(cherchermath.x)
print(cherchermath.y)
cherchermath.add(20,30)
cherchermath.product(45,25)

The output is:

importing-add-product-function

Python Immutability

The Advantages of Module

Python provides us several advantages by creating a module:

  • Code Reusability, because we write module only once but can import the module functionality at any number of times.
  • The length of the code will be automatically decreased and readability will be increased.
  • maintainability of the function will be increased.
Compiler version of the Module:
  • Whenever we are using any module in python for other programs then a separate compiler file will be created with the extension as .pyc
  • And this compiler version file will be generated.
  • The compiler file will be stored in a separate folder called _ _pycache_ _.
  • If the module will be used for times also the conversion will take place at once only and hence automatically the internal performance will be improved.
  • We can also visible this compiler file in our local system, just go to command prompt and pass the command as cd __pycache__, python will take you to __pycache__ folder

moving-to-pycache-folder

  • Just move to __pycache__ folder and click on that folder, you will see the converted version of the files cherchermath.py and demo8 file.
    files-inside-the-pycache-module

Functions

Module Aliasing

Creating a duplicate name for the Module which reduces the length of the code and hence the performance of the function will be increased.

To define the module aliasing we will use as keyword.

We have already created a module by the name cherchermath, let us import that module with duplicate names.

import cherchermath as M
print(M.x)
M.add(78,89)

The output is:

aliasing-concept

Once we define the alias name, we cannot use the original name of the module, if try to access any function by using the original name, python will throw a name error

import cherchermath as M
print(M.x)
M.add(78,89)
cherchermath.product(3*7)

The output is:

name-error-in-aliasing

Install pyDev with eclipse

Accessing the members of the Module by using from....import

We can access the members of the module by using the from...import.

The advantage of using this keyword is that we can directly access the members without a module name.

Example:

from cherchermath import x,y,add,product
print(x)
print(y)
add(50,60)
product(45,4)

The output is:

from-import

We can import all the members of the module by using *.

from cherchermath import*
print(x)
print(y)
add(50,60)
product(45,4)

The output is:

import-using-star

Python Operator

Member Aliasing

We can access the function of a module with the duplicate names by using the as a keyword, this process will also reduce the length of the code and hence the performance will increase.

from cherchermath import add as a,product as p
a(50,60)
p(45,4)

The output is:

member-aliasing

Various Possibilities of Importing a Statement:
  • import modulename
  • import module1,module2,module3
  • import module1 as m
  • import module1 as m1,module2 as m2,module3
  • from module import member
  • from module import member1,member2,memebr3
  • from module import memeber1 as x
  • from module import *

None Datatype

Module Name conflicts

If two modules having members with the name(variable name/function name), then there may be a chance of conflicts while accessing the member of the module, so to overcome this conflicts python provides some rules while accessing the members of the module such as:

Create a Module1:

def add(a,b):
    print("Module1 add function")
    print("The sum:",a+b)

Create a Module2:

def add(a,b):
    print("Module2 add function")
    print("The sum:",a+b)

Now create newtester file and import module1 and module2 add function

from module1 import*
from module2 import*
add(10,20)

Now the python will consider the most recent module function and prints the result

newtester-result

If we consider the module1 as the most recent one then

from module2 import*
from module1 import*
add(10,20)

The output is:

most-recent-module1

If we want both the modules to be available in the program, we can do it in two ways:

Solution1:

import module1
import module2
module1.add(10,20)
module2.add(10,20)

The output is:

avail-two-modules

Solution2:

from module1 import add as a1
from module2 import add as a2
a1(10,20)
a2(10,20)

The output is:

solution-two

Python Special Characters

Reloading a Module

The python module will be loaded inside the python virtual machine when we import it for the first time itself. Then we can use it for several times.

The advantage of the Reloading Module is, the performance of the function will be increased.

But the disadvantage is that, if the Module got updated and we are still using the old copy of the module because it won't reload again and hence the updated version may not be available for the new program.

The following example demonstrates the reloading of a module.

Consider the modulea contains the only add() function

def add(a,b):
    print("The sum:",a+b)

Now, I am importing the modulea in the below program and also I am importing the time module and make it sleep for 30 sec, in that sleeping time, I will update the modulea with the product() function

import time
import modulea
modulea.add(10,30)
time.sleep(30)

The output is:

result-of-importing-function

Now, I am going to update the modulea with product() function

def add(a,b):
    print("The sum:",a+b)
    
def product(a,b):
    print("The sum:",a*b)

Let us import this updated modulea in the result.py program

import time
import modulea
modulea.add(10,30)
time.sleep(30)
import modulea
modulea.product(3,4)

Now, the output is:

not-importing-product-function

So, from the above result, we can conclude that The python module will be loaded inside the python virtual machine when we import it for the first time itself

We have reload() which is present in the imp module, by using this function we can solve the above problem.

Now import a reload() function in result.py file and execute this program.

from imp import reload
import time
import modulea
modulea.add(10,30)
print("Enter into sleeping state")
time.sleep(30)
print("Just wakeup..trying to use modulea again")
reload(modulea)
modulea.product(3,4)

The output is:

using-reload-function

Python Datatype Summary

Finding the Members of the Module by using dir() function

The dir() function is used to find all the members present in the module, we can use this function in two ways.

If we use dir() function without passing any parameter, then the dir() function list out all the members of the current module.

If we use the dir(modulename) function, this function will list out all the members of the specified module.

The following example demonstrates finding all the members of the module

x=888
y=999
def add(a,b):
    print(a+b)
print(dir())

The output is:

using-dir-function-without-parameter

If you observe the above output, it is in the form of list datatype and hence the return type of dir() function is List Datatype.

The difference between dir() function and help() function

dir() help()
The dir() function just list out all the members of the given module. The help() function provides the documentation related to that module.

import math

print(dir(math))

import math

print(help(math))

The output of print(dir(math)) is:

import-math-function

The output of print(help(math)) is:

import-help-math-module

For every module at the time of execution Python interpreter will add some special properties automatically for internal use.
Example: __builtins__,__cached__,'__doc__,__file__, __loader__, __name__,__package__,
__spec__

Based on the requirement programmers also can access these properties in our programs

print(__builtins__ )
 print(__cached__ )
 print(__doc__)
 print(__file__)
 print(__loader__)
 print(__name__)
 print(__package__)
 print(__spec__)

The output is:

special-properties-added-by-pvm

The __doc__ is used to hold the string present in the document.

"This module contain some built-in members demo example"
print(__doc__)

The output is:

doc-member-output

The __file__ displays the current module filename

print("File name:",__file__)

The output is:

printing-file-name-using-file-fun

Python Output statements

The special variable __name__

The __name__ variable describes whether the program is executing directly or indirectly, that means an individual program or as a module.

If the variable value is __main__ then the program is executing directly and if the variable value is its module name then the program is executing indirectly.

Let us create a module by the name directcopy.py

print(__name__)

And execute this module directly from the command prompt and the output value should be __main__

direct-execution-of-module

Now create another file and import the above module(directcopy.py)and execute it

import directcopy
print("Test Module")

The output is:

indirect-execution-of-module

The following example demonstrates the __name__ variable

if __name__=="__main__":
     print("Direct Execution like main program")
else:
    print("Indirect Execution because of import statement")

The above one is a module when we execute it directly the output is:

direct-execution-of-module-again

Importing the above module in a program and executing it

import directcopy
print("Test Module")

The output is:

indirect-execution-of-module-again

The following example demonstrates the __name__ variable where the Module contains internally three functions and when we execute it directly it will display all the three functions but when we import this module in other program depending on the user requirement he may call any of the function but due to import statement all the three functions will execute with the required call function.

So to overcome this problem we can use an if condition in the module to execute respective functions only when the user is going to call the function.

Step 1: Creating a Module with the functions internally.

def function1():
    print("Function1 execution...")
def function2():
    print("Function2 execution...")
def function3():
     print("Function3 execution...")

function1()
function2()
function3()

When we execute the above module directly, the output is:

directcopy1-program

Now import this module in the other program and try to execute it

import directcopy1
directcopy1.function1()

The output is:

indirectcopy1-program

So, to overcome this problem we can use an if condition in the Module, so that when we import this module, it will print only the called functions.

def function1():
    print("Function1 execution...")
def function2():
    print("Function2 execution...")
def function3():
     print("Function3 execution...")
if __name__=="__main__":
    function1()
    function2()
    function3()

The output is:

after-if-condition-in-directcopy

Now, if you try to import the above module, it will print only the called function

import directcopy1
directcopy1.function1()

The output is:

after-if-condition-executing-indirect-program

Working with Math Module:

Python provides inbuilt module math. This module defines several functions that can be used for mathematical operations.

The main important functions are:

sqrt(x) 
ceil(x)
floor(x)
fabs(x)
log(x) 
sin(x) 
tan(x)

Example:

from math import *
print(factorial(4))
print(sqrt(4))
print(fabs(-10.6))
print(fabs(10.6))
print(ceil(10.5))
print(floor(10.5))

The output is:

output-of-mathmodule

The following example demonstrates finding the radius of the circle by using the math module

from math import *
radius=int(input("Enter Radius of the circle:"))
area=pi*pow(radius,2)
print("Area of the circle:", area)

The output is:

finding-the-radius-of-the-circle

Ways to Access the String Characters

Working with Random Module

This module defines several functions to generate random numbers, random objects, etc...We can use these functions while developing games, cryptography and to generate random numbers on the fly for authentication.

There are several functions available in the Random Module, here we will discuss five important functions of Random Module:

  • random() Function
  • uniform() Function
  • randint() Function
  • randrange() Function
  • choice() Function
random() Function:

This function is always going to return the float value which is between 0 and 1(not inclusive) that means. The random () function always returns the value between 0<x<1

The following examples demonstrate the random function

from random import *
for i in range(10):
    print(random())

The output is:

random-function-output

uniform() Function:

It returns random float values between 2 given numbers (not inclusive)

The value will be always between begin<x<end

Example:

from random import *
for i in range(10):
    print(uniform(1,10))

The output is:

uniform-function

randint() Function:

To generate a random integer between two given numbers(inclusive)

Example:

from random import *
for i in range(10):
    print(randint(1,50))

The output is:

randint-function

randrange() Function:
  • Returns a random number in the range between (begin, end, step)
  • begin <= x < end
  • Begin argument is optional and the default value is 0
  • End argument is optional and the default value is 1
  • randrange(10)-->generates a number from 0 to 9
  • randrange(1,11)-->generates a number from 1 to 10
  • randrange(1,11,2)-->generates a number from 1,3,5,7,9

Example:

from random import *
for i in range(10):
    print(randrange(1,11))

The output is:

randrange-function

choice() function:

The choice() function won't return any number instead it returns a random object from the Tuple, string, List, Etc...

Example:

from random import *
fruits=["Apple", "Banan", "Orange", "Mango", "Pappaya"]
print(choice(fruits))

The output is:

choice-function

The choice() function will not support set and dictionary datatypes.

from random import *
fruits={"Apple","Banana" ,"Orange" ,"Mango", "Pappaya"}
print(choice(fruits))

The output is:

set-datatype-doesnot-support-choice-function

The following example to generate 6 digits random number to use as an OTP

from random import *
print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),sep='')

The output is:

program-to-generate-six-digit-otp

If we want to print ten, six-digit OTP then

from random import *
for i in range(10):
    print(randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),randint(0,9),sep='')

The output is:

ten-six-digit-otp

We can also write a code to generate the same OTP in another way

from random import *
otp=''
for i in range(6):
    otp=otp+str(randint(0,9))
print(otp)

The output is:

second-approach-to-generate-otp

Write a program to generate a random password of length 6, where 1,3,5 characters are alphabet symbols and 2,4,6 characters are digits.

from random import *
alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits="0123456789"
print(choice(alphabets),choice(digits),choice(alphabets),choice(digits),choice(alphabets),choice(digits),sep='')

The output is:

otp-with-digits-and-numbers

Write a Program to Generate Fake Employee Data for Database Testing

Every employee data should contain datils :

  • Employee Name
  • Employee Number
  • Employee Salary
  • Employee City
  • Employee Mobile Number
  • Designation

Employee Name Requirements:

  • The Name should contain 3 to 10 character
  • First Should Character should be upper case and the remaining characters should be lower case.

Employee Number Requirements :

  • The employee number should start with e- followed by digits
Example:e-4567

Employee salary Requirement :

  • The employee salary should be between 10000 to 50000.

Employee City Requirements :

  • Employee city should be from Bangalore, Chennai, Hyderabad,
    Delhi, Mumbai, Pune

Employee Mobile Number Requirements :

  • The Mobile should contain exactly 10 digits and the first number should start with either 6 or 9.
Example: 9856463325,6578940333

Designation Requirements :

  • Employee Designation Should be From:["software Engineer", "Senior Software Engineer", "Project Lead", "Team Lead", "Project Manager"]
from random import *
alphabets="abcdefghijklmnopqrstuvwxyz"
digits="0123456789"
cities=["Bangalore", "Chennai", "Hyderabad", "Delhi", "Mumbai", "Pune"]
designations=["software Engineer", "Senior Software Engineer", "Project Lead", 
              "Team Lead", "Project Manager"]
def get_fake_name():
    name=choice(alphabets).upper()
    n=randint(2,9)
    for i in range(n):
        name=name+choice(alphabets)
    return name

def get_fake_eno():
    eno="e-"
    for i in range(4):
        eno=eno+choice(digits)
    return eno

def get_fake_salary():
    esal=uniform(10000,50000)
    return esal        
    
def get_fake_city():
    city=choice(cities)
    return city

def get_fake_mno():
    mno=choice("6789")
    for i in range(9):
        mno=mno+choice(digits)
    return mno   

def get_fake_designation(): 
    designation=choice(designations)
    return designation       

def get_fake_emp_data():
    print("Employee name:", get_fake_name())
    print("Employee eno:", get_fake_eno())
    print("Employee salary:", get_fake_salary())
    print("Employee city:", get_fake_city())
    print("Employee mno:", get_fake_mno())
    print("Employee designation:",get_fake_designation())
get_fake_emp_data()  

The output is:

fake-emp-data-one

If we want to print ten employee data then we can use for loop.

from random import *
alphabets="abcdefghijklmnopqrstuvwxyz"
digits="0123456789"
cities=["Bangalore", "Chennai", "Hyderabad", "Delhi", "Mumbai", "Pune"]
designations=["software Engineer", "Senior Software Engineer", "Project Lead", 
              "Team Lead", "Project Manager"]
def get_fake_name():
    name=choice(alphabets).upper()
    n=randint(2,9)
    for i in range(n):
        name=name+choice(alphabets)
    return name

def get_fake_eno():
    eno="e-"
    for i in range(4):
        eno=eno+choice(digits)
    return eno

def get_fake_salary():
    esal=uniform(10000,50000)
    return esal        
    
def get_fake_city():
    city=choice(cities)
    return city

def get_fake_mno():
    mno=choice("6789")
    for i in range(9):
        mno=mno+choice(digits)
    return mno   

def get_fake_designation(): 
    designation=choice(designations)
    return designation       

def get_fake_emp_data():
    print("Employee name:", get_fake_name())
    print("Employee eno:", get_fake_eno())
    print("Employee salary:", get_fake_salary())
    print("Employee city:", get_fake_city())
    print("Employee mno:", get_fake_mno())
    print("Employee designation:",get_fake_designation())
   
for i in range(10):
        get_fake_emp_data()
        print()   

The output is:

printing-ten-emp-data

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions