Working with Python Modules and Packages

August 06, 2025   7 Min Read 15

What You'll Learn

  • What are modules and why they're useful
  • How to use built-in Python modules like math, random, datetime, etc.
  • How to create your own modules
  • Understanding and building Python packages
  • How to import specific elements (from ... import)
  • Directory structure of a real Python package
  • Best practices in modular programming

What is a Module?

A module is simply a Python file (.py) containing functions, variables, or classes that you can reuse in other files.

💡 Helps organize your code better and promotes reusability.

Example: Creating and using a Module

math_tools.py


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

main.py


import math_tools
print(math_tools.add(3, 4))  # 7
print(math_tools.multiply(2, 5))  # 10

Built-in Python Modules (No Installation Needed)

Python provides hundreds of pre-built modules.

ModuleDescription
mathMathematical Operations
randomGenerate random values
datetimeWork with date and time
osInteract with operating system
sysSystem-Specific parameters
jsonHandle JSON data

Example: math and random


import math
import random


print(math.sqrt(16))  # 4.0
print(random.randint(1, 10))  # Random number between 1-10

Importing from Modules

You can import specific function instead of the whole module:


from math import sqrt, pow
print(sqrt(49))  # 7.0
print(pow(2, 3))  # 8.0

You can also alias functions:


import datetime as dt
print(dt.datetime.now())

What is a Python Package?

A package is a directory that contains multiple related modules. It must have an __init__.py file (can by empty) to be recognized as a package.

Example Directory Structure


my_package/
├── __init__.py
├── math_tools.py
├── string_tools.py

Usage in another file:


from my_package import math_tools
print(math_tools.add(5, 6))

🏗 Create Your Own Package (Step-by-Step)

  1. Create a folder: my_package/
  2. Add a blank file __init__.py
  3. Add modules like math_ops.py, file_ops.py
  4. Use it in your main program

🛠 Task for You

  1. Create a package called utilities
  2. Add a module file_utils.py with functions:
    • read_file(filepath)
    • write_file(filepath, content)
  3. Import it in a separate script and use the functions.

✔ Best Practices

  • Group related functions in a module
  • Use packages for project structure
  • Use meaningful module and function names
  • Avoid circular imports
  • Use __init__.py to initialize packages or define what gets imported

Summary

ConceptDescription
ModuleA .py file with functions/classes
PackageA folder of releated modules with __init__.py
Built-inModules like math, os, random, etc.
CustomYour own .py modules or package
importBrings in an entire module
fromImports specific items from a module

Leave a Reply