Python Modules and Packages

Introduction

Python becomes powerful when you organize code into modules and packages. This tutorial teaches you how Python loads external files, how imports work, and how to structure real projects like a pro.

1. What Is a Module?

A module is simply a Python file (.py) that contains functions, classes, or variables.

# file: math_utils.py
def add(a, b):
    return a + b
    

Importing a Module

import math_utils
print(math_utils.add(5, 3))
    

Importing Specific Items

from math_utils import add

print(add(10, 20))
    

2. What Is a Package?

A package is a collection of modules inside a folder containing an __init__.py file.

myapp/
 ├─ utils/
 │   ├─ __init__.py
 │   ├─ math_utils.py
 │   └─ string_utils.py
 └─ main.py
    

Using Modules from a Package

from utils.math_utils import add
print(add(1, 2))
    

3. __init__.py Explained

__init__.py marks a folder as a package. It can also run initialization code or re-export functions.

# utils/__init__.py
from .math_utils import add
    
Now you can do:
from utils import add
    

4. Installing External Packages with pip

pip install requests
    

Using an Installed Package

import requests

response = requests.get("https://example.com")
print(response.status_code)
    

5. Creating Your Own Installable Package

Basic structure:

mypackage/
 ├─ mypackage/
 │   ├─ __init__.py
 │   └─ core.py
 └─ setup.py
    

setup.py Example

from setuptools import setup, find_packages

setup(
    name="mypackage",
    version="1.0.0",
    packages=find_packages()
)
    

Summary