Modules in Python

Lavlesh Singh
5 min readSep 5, 2021

A group of functions, variables and classes saved to a file, which is nothing but module. Every Python file (.py) acts as a module.

Modules enable you to split parts of your program in different files for easier maintenance and better performance.

In Python, Modules are simply files with the “.py” extension containing Python code that can be imported inside another Python Program.

In simple terms, 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.

With the help of modules, we can organize related functions, classes, or any code block in the same file. So, It is considered a best practice while writing bigger codes for production-level projects in Data Science is to split the large Python code blocks into modules containing up to 300–400 lines of code.

The module contains the following components:

1- Definitions and implementation of classes,
2- Variables, and
3- Functions that can be used inside another program.

As a beginner, you start working with Python on the interpreter, later when you need to write longer programs you start writing scripts. As your program grows more in the size you may want to split it into several files for easier maintenance as well as reusability of the code. The solution to this is Modules. You can define your most used functions in a module and import it, instead of copying their definitions into different programs. A module can be imported by another program to make use of its functionality. This is how you can use the Python standard library as well.

Simply put, a module is a file consisting of Python code. It can define functions, classes, and variables, and can also include runnable code. Any Python file can be referenced as a module. A file containing Python code, for example: test.py, is called a module, and its name would be test.

There are various methods of writing modules, but the simplest way is to create a file with a .py extension which contains functions and variables.

How to create Python Modules.

Example-
calculator.py
x=888

def add(a,b):
print(“The Sum:”,a+b)

def product(a,b):
print(“The Product:”,a*b)

calculator module contains one variable and 2 functions.
If we want to use members of module in our program then we should import that module.
import modulename
We can access members by using module name.
modulename.variable
modulename.function()

test.py:
import calculator
print(calculator.x)
calculator.add(10,20)
calculator.product(10,20)
Output
888
The Sum: 30
The Product: 200

whenever we are using a module in our program, for that module compiled file will be generated and stored in the hard disk permanently.

Renaming a module.

Example
import calculator as calc
here calculator is original module name and calc is alias name.
We can access members by using alias name calc
test.py:
import calculator as calc
print(m.x)
m.add(10,20)
m.product(10,20)
from … import:
We can import particular members of module by using from … import .
The main advantage of this is we can access members directly without using module name.
Example
from calculator import x,add
print(x)
add(10,20)
product(10,20)==> NameError: name ‘product’ is not defined
We can import all members of a module as follows
from calculator import *
test.py:
from calculator import *
print(x)
add(10,20)
product(10,20)

The import statement

To use the functionality present in any module, you have to import it into your current program. You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name. First, let’s see how to use the standard library modules. In the example below,math module is imported into the program so that you can use sqrt() function defined in it

import math #You need to put this command,`import` keyword along with the name of the module you want to import
num = 4
print(math.sqrt(num)) #Use dot operator to access sqrt() inside module “math”

For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter, if it’s just one module you want to test interactively, use reload(), for example: reload(module_name).

Writing Modules

Now that you have learned how to import a module in your program, it is time to write your own, and use it in another program. Writing a module is just like writing any other Python file. Let’s start by writing a function to add/subtract two numbers in a file calculation.py.

def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)

If you try to execute this script on the command line, nothing will happen because you have not instructed the program to do anything. Create another python script in the same directory with name module_test.py and write following code into it.

import calculation #Importing calculation module
print(calculation.add(1,2)) #Calling function defined in add module.

If you execute module_test.py, you will see “3” as output. When the interpreter came across the import statement, it imported the calculation module in your code and then by using the dot operator, you were able to access the add() function.

Tere are more ways to import modules:

from .. import statement
from .. import * statement
renaming the imported module

Module Search Path

You may need your modules to be used in different programs/projects and their physical location in the directory can be different. If you want to use a module residing in some other directory, you have some options provided by Python.
When you import a module named calculation, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named calculation.py in a list of directories given by the variable sys.path.

sys.path contains these locations:

1- the directory containing the input script (or the current directory).
2- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
3- the installation-dependent default.

Assume module_test.py is in the /home/datacamp/ directory, and you moved calculation.py to /home/test/. You can modify sys.path to include /home/test/ in the list of paths, in which the Python interpreter will search for the module. For this, You need to modify module_test.py in following way:

import sys
sys.path.append(‘/home/test/’)

import calculation
print(calculation.add(1,2))

Byte Compiled Files

Importing a module increases the execution time of programs, so Python has some tricks to speed it up. One way is to create byte-compiled files with the extension .pyc.
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. 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.
Note that these .pyc files are usually created in the same directory as the corresponding .py files. If Python does not have permission to write to files in that directory, then the .pyc files will not be created.

dir() function

The dir() function is used to find out all the names defined in a module. It returns a sorted list of strings containing the names defined in a module.

import calculation
print(test.add(1,2))
print(dir(calculation))

In the output, you will see the names of the functions you defined in the module, add & sub. Attribute __name__ contains the name of the module. All attributes beginning with an underscore are default python attributes associated with a module.

Thanks for Reading this blog !!

https://medium.com/analytics-vidhya/java-vs-scala-7ff9eb50141

--

--