Python Modules and Packages

python
fundamentals
modules
Understanding Python modules, packages, and imports
Author

Mohammed Adil Siraju

Published

September 18, 2025

What are Modules?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added.

# Example: Using built-in modules
import math
import datetime

# Using math module
print(f"Pi value: {math.pi}")
print(f"Square root of 16: {math.sqrt(16)}")

# Using datetime module
now = datetime.datetime.now()
print(f"Current time: {now}")
Pi value: 3.141592653589793
Square root of 16: 4.0
Current time: 2025-09-18 11:56:02.592034

Import Statements

There are several ways to import modules in Python:

# 1. Import entire module
import numpy

# 2. Import with alias
import numpy as np

# 3. Import specific functions
from math import sqrt, pi

# 4. Import all (not recommended)
# from math import *

# Examples
arr = np.array([1, 2, 3, 4, 5])
print(f"Array: {arr}")
print(f"Mean: {np.mean(arr)}")

print(f"Using imported sqrt: {sqrt(25)}")
print(f"Using imported pi: {pi}")
Array: [1 2 3 4 5]
Mean: 3.0
Using imported sqrt: 5.0
Using imported pi: 3.141592653589793

Creating Custom Modules

You can create your own modules by saving Python code in a .py file.

# Example: Creating a simple utility module (conceptually)
# This would be saved as utils.py

def greet(name):
    """Greet a person by name"""
    return f"Hello, {name}!"

def calculate_area(radius):
    """Calculate area of a circle"""
    import math
    return math.pi * radius ** 2

# Constants
VERSION = "1.0.0"
AUTHOR = "Mohammed Adil Siraju"

# Test the functions
print(greet("Adil"))
print(f"Area of circle with radius 5: {calculate_area(5):.2f}")
print(f"Module version: {VERSION}")
Hello, Adil!
Area of circle with radius 5: 78.54
Module version: 1.0.0

Packages

A package is a collection of modules organized in directories. Packages help organize related modules together.

# Example package structure:
# mypackage/
#     __init__.py
#     module1.py
#     module2.py
#     subpackage/
#         __init__.py
#         submodule.py

# Importing from packages
# import mypackage.module1
# from mypackage import module2
# from mypackage.subpackage import submodule

print("Package structure example shown above")
Package structure example shown above

Best Practices

  1. Use descriptive names for modules and packages
  2. Keep modules focused on a single responsibility
  3. Use __init__.py to control package imports
  4. Document your modules with docstrings
  5. Follow PEP 8 naming conventions
  6. Avoid circular imports

Key Takeaways

  • Modules help organize and reuse code
  • Packages group related modules together
  • Import statements control what code is available
  • Python’s standard library provides many useful modules
  • Third-party packages extend Python’s capabilities

Next: We’ll explore Python functions and classes in detail.