Modules and Packages in Python

22 Mar 2026, Updated: 14 Jul 2026 4 min read
0
As your Python projects grow, managing code in a single file becomes difficult. To keep your code organized, reusable, and maintainable, Python provides modules and packages.

They allow you to divide your program into multiple files and reuse functionality across projects.

What is a Module?

A module is a Python file that contains functions, classes, and variables you can reuse in other programs. Modules help structure your code logically. Example:

Let's create a file named math_utils.py:
# math_utils.py
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b
Now, you can import and use this module in another file:
# main.py
import math_utils

print(math_utils.add(5, 3))       # Output: 8
print(math_utils.multiply(4, 6))  # Output: 24
Here, math_utils is a module.

Importing Modules

There are different ways to import a module in Python.
Syntax Description Example
import module_name Imports the entire module
# main.py
import math_utils

print(math_utils.add(5, 3))       # Output: 8
print(math_utils.multiply(4, 6))  # Output: 24
from module_name import function_name Imports specific functions
# main.py
from math_utils import add, multiply

print(add(5, 3))       # Output: 8
print(multiply(4, 6))  # Output: 24
from module_name import * Imports all functions (not recommended)
# main.py
from math_utils import *

print(add(5, 3))       # Output: 8
print(multiply(4, 6))  # Output: 24
import module_name as alias Imports a module with a short name
# main.py
import math_utils as math

print(math.add(5, 3))  # Output: 8
print(math.multiply(4, 6))  # Output: 24

The __name__ == "__main__" Construct

In Python, every file (module) has a built-in variable called __name__. When you run a Python file directly, Python automatically sets __name__ to "__main__".

When you import that same file into another Python file, __name__ is set to the module's name, not "__main__".

In simple words:
- If the file is being run directly, __name__ == "__main__" β†’ True
- If the file is being imported, __name__ == "__main__" β†’ False

This allows us to write code that behaves differently when imported vs executed directly.
Example:
#main_program.py
def greet():
    print("Hello from greet()!")

if __name__ == "__main__":
    print("Running directly...")
    greet()
else:
    print("Running via import...")
Case 1 β€” Run directly:
python main_program.py
Output:
Running directly...
Hello from greet()!
Case 2 β€” Import into another file:
#import_test.py
import main_program
python import_test.py
Output:
Running via import...

Why it's useful?

It allows you to separate reusable code from execution code. You can write:
- Functions, classes, and reusable logic (importable anywhere)
- And still test them in the same file safely

Real-life pattern:
def main():
    print("Program starts here!")

if __name__ == "__main__":
    main()
Ensures main() runs only when the file is executed, not when it’s imported by another module.

Built-in Modules

Python comes with a rich collection of built-in modules that make development faster and easier. Some popular ones include:
Module Purpose
math Mathematical operations
datetime Date and time handling
os File and directory management
sys System-specific parameters and functions
random Random number generation
json JSON data handling
re Regular expressions
Example:
import datetime

today = datetime.date.today()
print("Today's date:", today)

What is a Package?

A package is a collection of multiple Python modules grouped together in a directory. Packages help organize related code into a logical structure, making large applications easier to develop and maintain.

Starting with Python 3.3, a directory can be treated as a package even without an __init__.py file. Such packages are known as namespace packages.

Although __init__.py is now optional, it is still commonly used to perform package initialization, expose selected modules or functions, and define __all__.
Example: Directory Structure
my_package/
    __init__.py      # Optional
    calculator.py
    converter.py
# calculator.py
def add(a, b):
    return a + b
# converter.py
def km_to_miles(km):
    return km * 0.621371

Using the package:
# usage.py
from my_package import calculator, converter

print(calculator.add(5, 3))      # Output: 8
print(converter.km_to_miles(10)) # Output: 6.21371
You can also import individual modules or specific functions from a package:
from my_package.calculator import add

print(add(10, 20))   # Output: 30
If a package contains an __init__.py file, it can define the __all__ variable to control what gets imported when using the wildcard import.
# __init__.py
__all__ = ["calculator", "converter"]
When someone writes:
from my_package import *
Only the modules listed in __all__ (i.e., calculator and converter) are imported automatically.

Summary

Modules and Packages form the backbone of structured Python programming. They help you write cleaner, modular, and scalable applications.
Concept Description
Module A Python file (.py) containing reusable code
Package A directory containing multiple modules
import Used to bring external code into your program
__init__.py Optional package initialization file
__name__ == "__main__" Checks if a file is run directly or imported
Built-in Modules Pre-installed modules in Python’s standard library
In the next article, we'll explore File Handling in Python β€” reading, writing, and managing files efficiently.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer β€’ Java β€’ Python β€’ Distributed Systems β€’ AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

πŸ’¬ Comments

Join the Discussion