python modules and packages

module intro

  • python module is a python file contains a set of functions, variables and classes
  • modules are a way to organize the code based on the type of the functionality
  • improves the project structure and maintainability
  • improves code reusability

module usage

  • create a file named with basic math functionalities.

pi = 3.14

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b
  • we can use the functions in the above module in another module.
  • let's create a new module named and use the module calculator

import calculator

print(calculator.add(10, 20))
# output: 30
# output: 3.14
  • If we don't want to import complete module then we can import the required functions, variables, etc. using keywords from and import

Let's see the code for that

from calculator import add, pi

print(add(10, 20))
# output: 30
# output: 3.14

in-built python modules

package intro

  • A python package is a directory which collection of modules.
  • Modules that are related to each other are mainly put in the same package.
  • When a module from an external package is required in a program, that package can be imported and its modules can be put to use.
  • Package can contain a special file named which distinguishes a package from a directory

When you import a package, only the methods and the classes in the file of that package are directly visible.

package usage

  • Lets create a package named calci which contains modules like and
  • The package directory looks something like this
├── calci
│   ├──
│   ├──
│   └──
  • module contains functions like add, multiply, etc.
  • modules contains functions like celsius_to_fahrenheit, fahrenheit_to_celsius


def celsius_to_fahrenheit(celsius):
      fahr = (float(celsius) * 1.8) + 32
      return fahr

def fahrenheit_to_celsius(fahrenheit):
    celsius = (5 / 9 * fahrenheit - 32)
    return celsius


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

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

from calci.advanced import celsius_to_fahrenheit
from calci.basic import add

print(add(10, 20))
# output: 30
# output: 50.0
  • when we run the module it gives the ouptput.
  • packages are very useful when we have reusable functionality.

in-built python packages