Modules and Package Concepts in Python

By

 Today, we will learn about most important concepts of modules in python.

Modules in Python:-

  • A modules is a .py files containing definitions and statements. So all .py files that we created for our python programs are modules.
  • A python modules can be defined a python program file which contains .py files including python variable , class and functions etc.
  • A python modules provides us the flexibility to organize the code in a logical way.
e.g. Create a modules named as modules.py
def show ():
    print("Welcome to MNT LAB")
#calling the show() function
show()
Output:-
Welcome to MNT LAB
>>> 
The Main Modules:-
  • When we execute a program its module name is __main__.
  • This name is available in the variable __name__.
  • This technique is executed only when we run program directly and not executed when imported as a module.
  • When we run any python codes ,python interpreter start interpreting the codes inside it. At that time it sets some implicit variable values like math, random etc. ,one of them is __name__ whose value set as __main__.
  • If the program source file imported as a module , At that situation interpreter sets the __name__ value to module name. Then this main  method will not work.
e.g.
def display():
    print("I am display function")    
def show():
    print("I am show functions")
if (__name__== '__main__'):
    print(__name__)
display()
show() 
Output:-
__main__
I am display function
I am show functions
>>> 
The Multiple Modules:
There are two reasons why we may want to create a program that contains multiple modules as given below:-
  • It splits a big program into multiple .py files where each .py file acts as a module. This is ease of development and maintenance of program.
  • Suppose we want to use some functions in several programs in such case instead of copying these functions in different program files ,we may keep them in one fille  and used them in different program. This is helpful to reuse the existing code in multiple program.
The important python module:-
To use the definitions and statements in a module in another module, we need to import it into current module.
There are two ways to load the module in our python program as given below:-
  1. The import statement
  2. The form-import statement.
     1.) The import Statement:-This import statement is used to import all functionality of one module to another.So that we can import all functionality of one module to another .So that we can access the functionality of first module(.py) in second module(.py).We can import multiple modules within single statement or multiple statements.
syntax:-
import module 1,module 2,module 3.............................module n
                                          or
import module 1
import module 2
import module 3
. 
.
.
.
import module n
e.g.
1.) create a modules.py modules:-
def show ():
    print("Welcome to MNT LAB")
def display ():
    print("Welcome to www.msdotnet.co.in")   

2.) Create a functions.py Modules:-
def sum(a,b):
    c=a+b
    print("Sum of two numbers is:",c)
def subtraction(a,b):
    c=a-b
    print("Subtraction of two numbers is:",c)
def multiplication(a,b):
    c=a*b
    print("Multiplication of two numbers is:",c)
def division(a,b):
    c=a/b
    print("Division of two numbers is:",c)
def mod(a,b):
    c=a%b
    print("The modulous of given Number is:",c)
3.)  Create another modules calculate.py and call modules.py and functions.py modules as given below:-
#import modules,functions
import modules
import functions
modules.show()
modules.display()
#Take manual inputs from users
x=int(input("Enter the First integer value:"))
y=int(input("Enter the Second integer value:"))
functions.sum(x,y)
functions.subtraction(x,y)
functions.multiplication(x,y)
functions.division(x,y)
functions.mod(x,y)
Output:-
Welcome to MNT LAB
Welcome to www.msdotnet.co.in
Enter the First integer value:35
Enter the Second integer value:6
Sum of two numbers is: 41
Subtraction of two numbers is: 29
Multiplication of two numbers is: 210
Division of two numbers is: 5.833333333333333
The modulous of given Number is: 5
>>> 
Note :-
  • All module files should be created in same path (location) otherwise program gets error.
  • Here functions.py and modules.py  are called user defined module .You call built in modules also according to program requirements .some built in modules are math ,cmath, random  etc.
2.) The from-import statement:-
  • This concept is helpful to import a specific features or attributes of any module to another module, without importing whole module into python namespace.
  • Python  provides the flexibility, we can import only those specific attributes from other modules which is required in our program.
  • This makes the program faster and less memory consumption.
Syntax:-
from<module-name>import <att_name 1>,<att_name 2>...........<att_name n>
e.g.
  • First, i have created a attributes .py module.
  • Second, i have imported  multiplication() and division() specific attributes from functions.py module.
attributes.py
from functions import multiplication,division
#It will import only two attribute(multiplication,division) from functions.py modules
x=int(input("Enter first value:"))
y=int(input("Enter second value:"))
multiplication(x,y)
division(x,y) 
Output:-
Enter first value:30
Enter second value:6
Multiplication of two numbers is: 180
Division of two numbers is: 5.0
>>> 
Renaming a module:-
Python provides us the flexibility to rename your imported modules name in another program file as given below:-
Syntax:-
import<module_name>as <specific _name>
e.g.
1.) create a module function.py
def show ():
    print("I am show function")
def display ():
    print("I am display function")    
2.) create another module main.py and Rename the function.py module name as fun as shown in below codes:-
import function as fun
fun.display()
fun.show()
Output:-
I am display function
I am show function
>>> 
Symbol table:-
While  interpreting any program python interpreter create a symbol table .This concepts can understand those person whose knows about compiler design .In this concepts interpreter decide whether the operations performed by the identifier should be permitted or not.

Vars() and dir() functions:-
There are two global functions vars() and dir(). Both functions are built in function in python.
dir():- This function returns a sorted list.
e.g.
import function
import math
import random
a=1234
name="MNT LAB"
print(dir())
print(dir(math))
print(dir(function))
Output:-
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'function', 'math', 'name', 'random']
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'display', 'show']
>>> 
var():-This function returns a dictionary.
e.g.
import function
import math
a=1234
name="MNT LAB"
print(vars())
print(vars(math))
print(vars(function))
Output:-
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\RAMASHANKER VERMA\\Desktop\\vars function.py', 'function': <module 'function' from 'C:\\Users\\RAMASHANKER VERMA\\Desktop\\function.py'>, 'math': <module 'math' (built-in)>, 'a': 1234, 'name': 'MNT LAB'}
>>> 
Search Sequence of modules in python:-
To perform some basic operations,we generally import some modules in our programs.Suppose we have import two modules first is functions and second is math module.
  • Interpreter will first search built in modules after that search user defined modules.Here math is a built in module where functions is a user defined module.
  • If module is not found ,then it will search it in directory list which is available in sys.path.
Globals and Locals:-
  • An object is a nameless entity containing data and methods.
  • Method works with object data.
  • Variables that we create are identifiers that refer to an object data.
e.g. 
a= 50 ,here 50 is stored in a nameless object ,address of this maneless object is stored in the identifier a.
  • A  namespace is a dictionary of identifiers(keys) and their corresponding objects.
  • An identifier is used in a function or a method belongs to the local namespace.
  • An identifier is used outside a function or a method belongs to the global namespace.
  • If a local and a global identifier have the same name ,the local identifier override the global identifier.
  • If we wish to assign a value to a global identifier within a method ,we we should explicitly declare the variable as global using the global keyword.
e.g.
def func():
    #local identifier
    a=15
    #global identifier b
    global b
    b=5.23
    c="msdotnet"
    print(a,b,c)
#global identifiers
a=51
b=6.32
c="MNT LAB"
func()
print(a,b,c)
Output:-
15 5.23 msdotnet
51 5.23 MNT LAB
>>> 
Description:- Here the value of local identifier a and c override the value of global identifier a and c.
Global() and local() function in python
  • We can easily display the global and local namespaces using built in functions global() and local().
  • If local() function is called ,then it returns a dictionary of identifier that are accessible from that method or function.
  • If global() function is called then it returns a dictionary of a global identifiers that can be accessed from that method.
e.g.
def myfun():
    #local identifier
    a=50
    #global identifier b
    global b
    b=3.10
    c="www.msdotnet.co.in"
    print(locals())
    print(globals())
#global identifiers
a=125
b=10.32
c="MNT LAB"
myfun()
Output:-
{'a': 50, 'c': 'www.msdotnet.co.in'}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/RAMASHANKER VERMA/Desktop/global.py', 'myfun': <function myfun at 0x0000017DEEC66048>, 'a': 125, 'b': 3.1, 'c': 'MNT LAB'}
>>> 
Packages:-
  • To access the computer files in well defined manner and fast. we generally use use a well organized hierarchy of directories.
  • when we are working on large project,then it is necessary that palace the similar modules in one package and other modules in different packages.This makes the project easy and fast.
  • We know drives,folders and subfolders helps us to organize the files in an os.Similarly packages, sub-packages and modules are used to organize the files in well defined manner.
  • A particular directory is treated as a package if it contains the the __init__.py file.
  • The __init__.py files files may be empty or it can contains some initilization codes for the package.


Suppose we want to access the image,audio module and drive c sub-package,we can use the following codes as given below:-

import Directory.Drive D.image 
import Directory.Drive E.audio
import Directory.Drive C

Watch Complete Lecture Video:-

For More...

0 comments:

Post a Comment

Powered by Blogger.