Modules
Modules
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.
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.
You can use any Python source file as a module by executing an import statement
in some other Python source file.
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 −
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"]
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 )
Advantages of Modules
Some of the advantages while working with modules in Python is as follows:
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: dir() can be used on all the modules, even with the one which we create.
>>>import builtins
>>>dir(built-ins)
Example:
import math
Math Methods
Method Description
math.dist() Returns the Euclidean distance between two points (p and q),
where p and q are the coordinates of that point
math.expm1() Returns Ex - 1
math.fsum() Returns the sum of all items in any iterable (tuples, arrays,
lists, etc.)
math.isclose() Checks whether two values are close to each other, or not