MODULES
Module to be the same as a code library. It is a file containing a set of
functions you want to include in your application. A module can define functions,
classes and variables. A module can also include runnable code.
If you quit from the Python interpreter and enter it again, the definitions you have
made (functions and variables) are lost. Therefore, if you want to write a
somewhat longer program.
As your program gets longer, you may want to split it into several files for easier
maintenance. You may also want to use a handy function that you’ve written in
several programs without copying its definition into each program.
Python has a way to put definitions in a file and use them in a script or in an
interactive instance of the interpreter. Such a file is called a module.
In Python, Modules are simply files with the “.py” extension containing
Python code that can be imported inside another Python Program.
In short, we can consider a module to be the same as a code library or a file that
contains a set of functions that you want to include in your application.
The module contains the following components:
Definitions and implementation of classes,
Variables, and
Functions that can be used inside another program.
Each module has its own private namespace, which is used as the global
namespace by all functions defined in the module. Thus, the author of a
module can use global variables in the module without worrying about accidental
clashes with a user’s global variables.
On the other hand, if you know what you are doing you can touch a module’s
global variables with the same notation used to refer to its
functions,modulename.itemname.
Modules can import other modules. It is customary but not required to place
all import statements at the beginning of a module (or script, for that
matter). The imported module names, if placed at the top level of a
module (outside any functions or classes), are added to the module’s
global namespace.
Create Module in Python
Example:
#A simple module, calculator.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Import Module in Python
You can use any Python source file as a module by executing an import statement
in some other Python source file.
The import has the following syntax −
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path. A search path is a list of directories
that the interpreter searches before importing a module.
We can import the functions, and classes defined in a module to another module
using the import statement in some other Python source file.
Example:
# importing module calculator.py
import calculator
print(calculator.add(10, 2))
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is
used.
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
Example:
File1:
student1 =
{
"name": "Raghav",
"age": 20,
"country": "India"
}
Save as mymodule.py
File 2:
import mymodule
a = mymodule.student1["age"]
print(a)
The from-import Statement in Python
It is also possible to import all names from a module into the current namespace
by using the following import statement −
Importing specific attributes from the module
Syntax:
from modname import <function/attribute name>
Example:
from calculator import add
OR
Importing all attributes from the module
Syantax:
from modname import *
Example:
from calculator import *
This provides an easy way to import all the items from a module into the current
namespace.
Note: When importing using the from keyword, do not use the module
name when referring to elements in the module.
Example: student1["age"], not mymodule.student1["age"]
Renaming the Python module
We can rename the module while importing it using the keyword.
Syntax:
import Module_name as Alias_name
Example:
import calculator as calci
Local Namespace Vs Global Namespace
A Python statement can access variables in a local namespace and in
the global namespace. If a local and a global variable have the same
name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions.
The statement global VarName tells Python that VarName is a global variable.
Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the
function Money, we assign Money a value, therefore Python assumes Money as a
local variable.
Example:
Number = 204
def AddNumber():
# accessing the global namespace
global Number
Number = Number + 200
print( Number )
AddNumber()
print( Number )
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several
locations. Python interpreter searches for the module in the following manner:
First, it searches for the module in the current directory.
then searches each directory in the shell variable PYTHONPATH. The
PYTHONPATH is an environment variable, consisting of a list of directories.
At the end it checks the installation-dependent list of directories configured
at the time Python is installed.
Advantages of Modules
Some of the advantages while working with modules in Python is as follows:
Working with modules makes the code reusable.
break down large programs into small manageable and organized files
module focuses on a small proportion of the problem
allow you to organize python code
makes the code easier to understand and less complicated
“Compiled” Python files
To speed up loading modules, Python caches the compiled version of
each module in the _pycahe_ directory under the name module.version.pyc,
where the version encodes the format of the compiled file; it generally contains
the Python version number.
Python checks the modification date of the source against the compiled
version to see if it’s out of date and needs to be recompiled. This is a
completely automatic process.
Also, the compiled modules are platform-independent, so the same library can be
shared among systems with different architectures.
This .pyc file is useful when you import the module the next time from a
different program - it will be much faster since a portion of the processing
required for importing a module is already done. Also, these byte-compiled files
are platform-independent.
Internally, Python converts the source code into an intermediate form
called bytecode, it then translates this into the native language of your
computer and then runs it.
Python does not check the cache in two circumstances. First, it always recompiles
and does not store the result for the module that’s loaded directly from the
command line. Second, it does not check the cache if there is no source module.
Note: that these .pyc files are usually created in the same directory as the
corresponding .py files.
Note: To display a list of all of the available modules in Python Programming
Language, we can use the following command in the Python console:
help('modules')
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: dir() can be used on all the modules, even with the one which we create.
>>>import builtins
>>>dir(built-ins)
Python built-in modules
There are several built-in modules in Python, which you can import whenever
you like.
Example:
import math
print(math.sqrt(25)) #squareroot of number
print(math.factorial(5)) #factorial of number
print(math.pi) #value of pi
print(math.ceil(5.4)) #ceil value
print(math.floor(5.8)) #floor value
print(min(3, 10, 7, 4)) #minimum number
print(max(3, 10, 7, 4)) #maximum number
print(math.pow(5,3)) #power a^b
print(math.fmod(15,2)) #modulus
tpl1=(1,2,3,4,5)
print(math.fsum(tpl1)) # find sum of all elements of list/tuple/array
print(math.isnan(4)) #check whether argument passed in number or
not
Math Methods
Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
math.comb() Returns the number of ways to choose k items from n items
without repetition and order
math.copysign() Returns a float consisting of the value of the first parameter
and the sign of the second parameter
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
math.dist() Returns the Euclidean distance between two points (p and q),
where p and q are the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns Ex - 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays,
lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest
integer
math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the
given numbers x and i
math.lgamma() Returns the log gamma value of x
math.log() Returns the natural logarithm of a number, or the logarithm of
number to base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
math.perm() Returns the number of ways to choose k items from n items
with order and without repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.radians() Converts a degree value into radians
math.remainder() Returns the closest value that can make numerator
completely divisible by the denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number