modules and packages · 2020-04-13 · some functions of math modules 5 method description example...
TRANSCRIPT
Modules and Packages
1
Modular Programming q In Python, the modular programming is realized by by functions, modules and packages.
q Modular programming refers to the process of breaking a large, complexprogramming task into separate, smaller, more manageable subtasks or modules.
q Individual modules can also be combined together like building blocks to create a largerand complex application.
Advantages of modular Programmingq Simplicity: Rather than focusing on the entire problem at hand, a module typically
focuses on one relatively small portion of the problem.q Maintainability: If modules are written in a way that minimizes dependency, then it is
possible to modify a single module without affecting other parts of the program.q Reusability: Functionality defined in a single module can be easily reused by more than
one applications.q Scoping: Modules define a separate namespace, which helps avoid collisions between
identifiers in different areas of a program.
Module
q A module allows you to logically organize your Python code.q It groups related code into a module that makes the code easier to understand and
use.
Moduleq A module is a file consisting of Python code.q A module can define functions, variables and classes. q A module can also include runnable code.
The import keyword is used to include a moduleq Invoking functions from a moduleq Use the module name followed by the dot operator (.)
<moduleName>.<functionName( argument )>
q Module: Typesq Built-in : math, sys etc. q User-defined
3
Built-in Modulesq There are several built-in modules supported by Python. q Example: os, math, itertools, collections etc.
q How to check ?q help(‘modules’) – Provide complete list of all modulesq dir(<module_name>) – Provide complete list inside the module <module_name>.q help(<module_name>.<object_name>) – Provide help on <object_name> in
module <module_name>.
Examples:q help((‘modules’) )q dir(math)q help(math.sqrt)
4
Some functions of Math Modules
5
Method Description Example
acos( x ) Trigonometric arc cosine of x(result in radians)
acos( 1.0 ) is 0.0
asin( x ) Trigonometric arc sine of x(result in radians)
asin( 0.0 ) is 0.0
atan( x ) Trigonometric arc tangent of x(result in radians)
atan( 0.0 ) is 0.0
ceil( x ) Rounds x to the smallest integer
not less than xceil( 9.2 ) is 10.0ceil( -9.8 ) is -9.0
cos( x ) Trigonometric cosine of x(x in radians)
cos( 0.0 ) is 1.0
exp( x ) Exponential function ex exp( 1.0 ) is 2.71828exp( 2.0 ) is 7.38906
fabs( x ) Absolute value of x fabs( 5.1 ) is 5.1fabs( -5.1 ) is 5.1
floor( x ) Rounds x to the largest integer not
greater than xfloor( 9.2 ) is 9.0floor( -9.8 ) is -10.0
fmod( x, y) Remainder of x/y as a floatingpoint number
fmod( 9.8, 4.0 ) is 1.8
Some functions of Math Modules
6
hypot( x, y ) hypotenuse of a triangle with sidesof length x and y hypot( 3.0, 4.0 ) is 5.0
log( x ) Natural logarithm of x (basee) log( 2.718282 ) is 1.0log( 7.389056 ) is 2.0
log10( x ) Logarithm of x (base10) log10( 10.0 ) is 1.0log10( 100.0 ) is 2.0
pow( x, y) x raised to power y pow( 2.0, 7.0 ) is 128.0pow( 9.0, .5 ) is 3.0
sin( x ) trigonometric sine of x(x in radians)
sin( 0.0 ) is 0.0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x(x in radians)
tan( 0.0 ) is 0.0
User-Defined Modulesq All python files can be used as modules in other files.q The user can use any Python source file as a module by executing an import statement
in some other Python source file.
q The import has the following syntax −q import <module1>, <module2>, …, <moduleN>
q When the interpreter encounters an import statement, it imports the module if themodule is present in the search path.
q A search path is a list of directories that the interpreter searches before importing amodule.
User-Defined Modules#The file name is firstModule.py
A = [2, 3, 4]String = ‘BSc-II-Semester’
def factorial(number):
if number <= 1: #Base casereturn 1
else:#recursive callreturn number * factoria ( number - 1 )
#The file name is secondModule.py
def fibonacci( n ): if n < 0:
print ('Cannot find the fibonacci of a negative number number.')
elif n == 0 or n == 1: return n
else:# two recursive callsreturn fibonacci( n - 1 ) + fibonacci( n - 2 )
User-Defined Modules
import firstModule, secondModulex = int(input( "Enter first integer:" ))y = int(input( "Enter second integer:" ))
factValue = firstModule.factorial(x)print ('The factorial value of %d is %d'%(x, factValue))
fibNumber = secondModule.fibonacci(y)print ('The %d th fibonacci number is %d'%(y, fibNumber))
Specific/All FunctionsIf you want to import some function into your program directly in order to avoid typing the modulename everytime for it, then you can use the following statements .
from <modulename> import <functionname>/<varablename>It allows you to import specific attributes from a module into the current namespace.
Example:from math import sqrt
This statement does not import the entire module math into the current namespace; it just introduces the sqrt function from the module math into the global space.
Now, you can use sqrt function with math.
It is also possible to import all names from a module into the current namespace by using the following import statement −
from <modulename> import *
Example#import firsModule, secondModule
from firstModule import factorialfrom secondModule import fibonacci
x = int(input( "Enter first integer:" ))y = int(input( "Enter second integer:" ))
#factValue = firstFile.factorial(x)factValue = factorial(x)
print ('The factorial value of %d is %d'%(x, factValue))
#fibNumber = secondFile.fibonacci(y)fibNumber = fibonacci(y)print ('The %d th fionaccin number is %d'%(y, fibNumber))
We are using from firstModule import factorial.This is the reason not using module before the factorial.
Similarly, for the from secondModule import fibonacci
Locating Modules
When you import a module, the Python interpreter searches for the module in the followingsequences−
• The current directory.• If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.• If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.The module search path is stored in the system module sys as the sys.path variable. Thesys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
Modulesq Each module has its own private symbol table, which creates a separate namespace.q The statement import <module_name> only places <module_name> in the caller’s symbol
table. The objects that are defined in the module remain in the module’s private symbol table.
import <module_name>q From the caller, objects in the module are only accessible when prefixed
with <module_name> via dot notation.
q After the following import statement, firstModule is placed into the local symbol table.Thus, firstFModule has meaning in the caller’s local context of python file (pfile.py):
q Example- pfile.py
q firstModule.py
import firstModulex = int(input( "Enter first integer:" ))
factValue = firstFile.factorial(x)
print ('The factorial value of %d is %d'%(x, factValue))A = [2, 3, 4]String = ‘BSc-II-Semester’
def factorial(number):if number <= 1: #Base case
return 1
else:#recursive callreturn number * factorial( number - 1 )
Run dir() beforeand after theexecution ofprogram.You can see thedifference
Modulesq Each module has its own private symbol table, which creates a separate namespace.q The statement import <module_name> only places <module_name> in the caller’s symbol table.
The objects that are defined in the module remain in the module’s private symbol table.
from <module_name> import <name>q It allows individual objects from the module to be imported directly into the caller’s symbol table.q Since, this form of import places the object names directly into the caller’s symbol table, any objects
that already exist with the same name will be overwritten.
q Example- firstModule.py
q Testfile.py
from firstModule import A, factorialx = int(input( "Enter first integer:" ))A = [600, 66, 550]print(A)factValue = factorial(x)print ('The factorial value of %d is %d'%(x, factValue))
A = [2, 3, 4]String = ‘BSc-II-Semester’
def factorial(number):if number <= 1: #Base case
return 1
else:#recursive callreturn number * factorial( number - 1 )
It will be overwritten because of the from firstModule import A, factorial
Modulesfrom <module_name> import *
q It imports all names from a module into the current namespace.q It isn’t recommended. It’s a bit dangerous because you are entering all names into thelocal symbol table that leads to conflict.
q It will overwrite all conflicting identifiers
Alternative names
To remove conflic between names, you can use alternative names for modules and every identifiers in modules.
1.import <module_name> as <new_name>
It allows you to use <module_name> with alternative name as <new_name>.
Example:import math as Mprint(M.sqrt())
2.from <module_name> import <function_name> as FN, <variable_name> as VA
It allows you to use identifier names with alternative names.
Example:from firstModule import A as Alist, factorial as newFactorialprint(A); print(newFactorial(5))
Python Packages
Python Packagesq The applications include several many modules which are difficult to manage if all of them
are stored into one location.q The modules with similar or related functionalities can be stored into packages.q Packages allow hierarchical structuring of the module namespace using dot notation.
q The basic idea for creating is shown by following Figure.
q The directory/folder package1 consists of three python modules.
Python PackagesA package1 is a folder in current folder(in path of Python)
A module named firstModule.py in package1
A module named secondModule.py in package1
A module named thirdModule.py in package1
q The directory/folder consists of three python modules.q Using this structure, the modules inside it can be accessed with dotnotation (pakage1.firstModule, pakage1.secondModule etc.)
q The modules from the packages can be import in usual way.
Python PackagesA package1 folder in current folder(in path of Python)
A module named firstModule.py in package1
A module named secondModule.py in package1
Python Packages
import package1.firstModule, package1.secondModule
x = int(input( "Enter first integer:" ))
y = int(input( "Enter second integer:" ))factValue = package1.firstModule.factorial(x)print ('The factorial value of %d is %d'%(x, factValue))
fibNumber = package1.secondModule.fibonacci(y)print ('The %d th fibonacci number is %d'%(y, fibNumber))
The package1 and this file are in current folder.
Both are in package1
Python Packages
from package1.firstModule import factorialFrom package1.secodModule import fibonacci
x = int(input( "Enter first integer:" ))
y = int(input( "Enter second integer:" ))factValue = factorial(x)print ('The factorial value of %d is %d'%(x, factValue))
fibNumber = fibonacci(y)print ('The %d th fibonacci number is %d'%(y, fibNumber))
The package1 and this file are current same folder.
Both are in package1
If we are using this form.
Dot notation is not required.
Python Packages
from <module_name> import * • This statement can also be used for packages.
Subpackages• -Packages can contain nested subpackages to arbitrary depth.
Thank You