Modules & Packages in Python

Module is that feature of python which makes the codes more efficient and reusable. A simple file with .py extension can be termed as a Python Module.

A module may be made up of function definitions, classes, variables or just an elementary piece of code.

The idea of creating Python modules is to divide a long python script(program) into several short and simplified programs, which are stored in the files called modules. It becomes much easier to manage a very long program, when it consists of multiple modules or sections, each performing a specific task.

Apart from simplifying the problem, modules reduce your typing work by providing reusability. The functionalities and capabilities of a module can be used in any other program by importing it. For this purpose, python already owns a huge collection of built-in modules.

These modules are stored in a directory named lib. It is present at the location where you have installed Python.

How to import a module in python?

A keyword import is used to import a module in a program, whereas to call the functions defined inside the imported module, the dot (.) operator is used. Well, there are different ways to use a module.

  • Importing the whole module

    Syntax:
    import module_name

    As the interpreter reads the above statement, it makes all the functions of the module accessible to the user.

    Example:

    import math
    num = 81
    result = math.sqrt(num)
    print('Square root of ', num, '=', result)

    Output:

    Square root of 81 = 9.0​
  • Importing only the specified function or functions

    Syntax:
    from module_name import function_name

    This statement lets you use only the specified functions of the module. Remember that, in this case, you do not need to call the function with the module name and the dot (.) operator.

    Example 1:

    #importing only one function
    
    from math import factorial
    result = factorial(5)
    print('Factorial of 5 =', result)

    Output:

    Factorial of 5 = 120

    Example 2:

    #importing only two functions
    
    from math import factorial, pi
    x = 5
    fact = factorial(x)
    area = pi * x * x
    print('Factorial of ',x,' =', fact)
    print('Area of circle with radius', x,'=', area)

    Output:

    Factorial of 5 = 120
    Area of circle with radius 5 = 78.53981633974483​
  • Importing all the functions of the module

    Syntax:
    from module_name import *

    This statement works like the previous one, but in this case, all the definitions of the module are imported.

    Example:

    from math import *
    print('Cube of 9 =', pow(9,3))

    Output:

    Cube of 9 = 729.0​
  • Giving a new name to the module

    Syntax:
    import module_name as new_name

    Python allows you to rename the imported module as per your comfort. You can change the name of the module if it is too long to type each time you call a function. But, once rename, you must use the new name only all over the code.

    Example:

    import math as q
    result = q.sqrt(64)
    print('Square root of 64 =', result)

    Output:

    Square root of 64 = 8.0

How to create a module in Python?

You can easily create a modulein python because modules are nothing but files of python source code.

For an instance, if you are working on such a script, where you find that a particular function or a set of functions is needed very frequently. Then, in order to make your code more efficient and less complicated, you must write a module containing those functions.

As a result, you can use the same module in multiple codes without rewriting the functions again and again.

The name by which you save the file acts as the name of the module.

Example: sample.py

def name():
    name = input(('What is your name?\n'))
    l = len(name)
    print('Length of your name =', l)
  • A python code containing a function 'name()' is created. This function takes the name of the user as a string, which is assigned to the variable n. In the next step, the length of the input string is calculated with len() function and assigned to the variable l.
  • The print statement displays the value of l as the output. This program is saved as sample.py.

On running this python file, no output will be generated. Now, we will create another program where we can import this module.

Example: module.py

import sample
print('This Program will find the length of the name you enter.')
sample.name()

Output:

This Program will find the length of the name you enter.
What is your name?
Shreya Agarwal
Length of your name = 14

You can see that the function name() is not defined in the above program. But, as we have imported the module sample, the function name() is accessible.

The dir() function

dir() is a built-in function which is used to view all the definitions present in a module. They are returned in the form of a list. The module name is passed as the argument to this function.

Let us find out all the definitions inside the math module.

Example:

>>> import math
>>> dir(math)

['__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']

Python Module Search Path

As the Python Interpreter finds the import statement, it starts looking for the module name in the built-in modules.

If the module is not present in the built-in modules, then the interpreter goes to a module called sys. Here, the search is performed over the set of directories contained in a variable sys.path in following sequence:

  1. Current Directory
  2. Shell Variable PYTHONPATH
  3. Installation Dependent Default Directory

Packages in Python

In python, modules of the same type can be grouped into a single entity called as Packages. Packages provide a proper, hierarchical arrangement of the directories. This makes it very easy to manage and work on large projects.

Every package contains a special file __init__.py whose presence indicates that the directory is a package. This file can be left vacant or you can place the initialization code of the package.

Let us take an example to understand the packages.

A package is created for Food which contains a file __init__() and 3 sub-packages named Pizza, Pasta and Icecream. Each of these sub-packages holds the __init__.py file and other modules as well.

How to import a module from a package in Python?

The modules stored within a package can be imported with the help of the (.) dot operator.

Syntax:
import package_name.module_name

To use a function defined inside a module:
Syntax:
package_name.module_name.function_name()

For example:

import Food.Pasta.Sauce #Importing the module
Food.Pasta.Sauce.add_sauce() #Using the function defined in a module

This statement shows the hierarchy of the package i.e Food>Pasta>Sauce. The module Sauce is imported from the package Pasta which is a sub-package of the package Food.