Getting Started with Modules and Packages in Python

Modules and packages are two important concepts in Python for organizing and managing source code. Here is a description of modules and packages and how to use them:



  • In Python, a module is a collection of definitions, functions, variables, and statements that are written to be used.
  • Each Python file can be considered a module and contains code related to a specific functionality.
  • You can use built-in Python modules or create your own modules to use in your code.

Example: Create a file named containing some math functions:

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

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

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

Then, you can use these functions in another program by importing the math_operations module:

import math_operations

result = math_operations.add(10, 5)
print(result)   # Output: 15



  • A package is a way to organize and group related modules together.
  • It is a directory that contains Python files (modules) and an empty file to indicate that the directory is a package.
  • Packages help organize your code into logical scopes and structured directories.

Example: Create a package named my_package, containing two modules and


In, we have the following code:

def greet(name):
    return f"Hello, {name}!"

In, we have the following code:

def calculate_square(num):
    return num ** 2

Then, you can use functions from modules in the my_package package as follows:

from my_package import module1, module2

message = module1.greet("Alice")
print(message)   # Output: Hello, Alice!

result = module2.calculate_square(5)
print(result)   # Output: 25

Using modules and packages helps you organize and manage your code efficiently, making it more readable and maintainable.