Python Project: Todo App
Build a fully-featured Todo App from scratch in Python! This project progressively adds real-world functionality — starting with a CLI task manager, building an OOP data model with dataclasses, adding JSON file persistence so tasks survive restarts, implementing priority levels and due dates, search and filter capabilities, and finally a rich terminal UI with colour-coded output. Every version applies the Python skills you've mastered across this course — making it a solid portfolio piece.
Project Overview — Architecture & Python Concepts
This project applies concepts from across the entire course. Here's the build roadmap, the app's data model, and the Python skills each version practices:
Version 1 — CLI Task Manager
Start with the fundamentals — a simple list of task dicts, a menu loop, and basic CRUD operations. Everything runs in memory (tasks are lost on exit — we fix that in v3).
# ── Todo App v1 — CLI with dicts ──────────────────────
tasks = []
_next_id = 1
def add_task(title: str) -> dict:
global _next_id
task = {"id": _next_id, "title": title, "done": False}
tasks.append(task)
_next_id += 1
print(f"✅ Added: '{title}' (id={task['id']})")
return task
def complete_task(task_id: int) -> bool:
for task in tasks:
if task["id"] == task_id:
task["done"] = True
print(f"☑️ Completed: '{task['title']}'")
return True
print(f"❌ Task {task_id} not found")
return False
def delete_task(task_id: int) -> bool:
for i, task in enumerate(tasks):
if task["id"] == task_id:
del tasks[i]
print(f"🗑️ Deleted task {task_id}")
return True
print(f"❌ Task {task_id} not found")
return False
def list_tasks(show_done: bool = True):
visible = tasks if show_done else [t for t in tasks if not t["done"]]
if not visible:
print(" No tasks found."); return
print(f"\n{'ID':<4} {'Status':<8} Title")
print("-" * 40)
for t in visible:
status = "✅ done" if t["done"] else "⬜ todo"
print(f" {t['id']:<3} {status:<8} {t['title']}")
print(f"\nTotal: {len(tasks)} | Done: {sum(1 for t in tasks if t['done'])}")
def main():
print("📝 Python Todo App v1")
print("Commands: add, done, del, list, quit\n")
while True:
cmd = input("todo> ").strip().lower()
if cmd == "quit": break
elif cmd == "list": list_tasks()
elif cmd.startswith("add "):
add_task(cmd[4:].strip())
elif cmd.startswith("done "):
try: complete_task(int(cmd[5:]))
except ValueError: print("Usage: done <id>")
elif cmd.startswith("del "):
try: delete_task(int(cmd[4:]))
except ValueError: print("Usage: del <id>")
else: print("Unknown command")
if __name__ == "__main__": main()
Version 2 — OOP Data Model with Dataclasses & Enums
Replace plain dicts with a proper Task dataclass and
a TodoList manager class. Use Enum for
status and custom exceptions for clean error handling.
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
import uuid
# ── Status Enum ───────────────────────────────────────
class Status(Enum):
TODO = "todo"
IN_PROGRESS = "in_progress"
DONE = "done"
# ── Task dataclass ────────────────────────────────────
@dataclass
class Task:
title: str
status: Status = Status.TODO
id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
tags: list[str] = field(default_factory=list)
def complete(self): self.status = Status.DONE
def start(self): self.status = Status.IN_PROGRESS
def is_done(self) -> bool: return self.status == Status.DONE
def __str__(self) -> str:
icons = {Status.TODO: "⬜", Status.IN_PROGRESS: "🔄", Status.DONE: "✅"}
tag_str = f" [{', '.join(self.tags)}]" if self.tags else ""
return f"{icons[self.status]} [{self.id}] {self.title}{tag_str}"
# ── Custom exceptions ─────────────────────────────────
class TaskNotFoundError(Exception): pass
class DuplicateTaskError(Exception): pass
# ── TodoList manager ──────────────────────────────────
class TodoList:
"""Manages a collection of Task objects."""
def __init__(self):
self._tasks: list[Task] = []
def add(self, title: str, tags: list[str] = None) -> Task:
title = title.strip()
if not title: raise ValueError("Task title cannot be empty")
task = Task(title=title, tags=tags or [])
self._tasks.append(task)
return task
def get(self, task_id: str) -> Task:
for t in self._tasks:
if t.id == task_id: return t
raise TaskNotFoundError(f"No task with id '{task_id}'")
def complete(self, task_id: str) -> Task:
task = self.get(task_id); task.complete(); return task
def delete(self, task_id: str) -> Task:
task = self.get(task_id)
self._tasks.remove(task); return task
@property
def all(self): return self._tasks.copy()
@property
def pending(self): return [t for t in self._tasks if not t.is_done()]
def stats(self) -> dict:
total = len(self._tasks)
done = sum(1 for t in self._tasks if t.is_done())
return {"total": total, "done": done,
"pending": total - done,
"pct": f"{done/total*100:.0f}%" if total else "0%"}
# ── Usage ─────────────────────────────────────────────
todo = TodoList()
t1 = todo.add("Learn Python decorators", tags=["python", "study"])
t2 = todo.add("Build portfolio project", tags=["career"])
t3 = todo.add("Read Python docs")
todo.complete(t1.id)
for task in todo.all:
print(task)
print(todo.stats()) # {'total': 3, 'done': 1, 'pending': 2, 'pct': '33%'}
Version 3 — JSON File Persistence
Add a JsonStorage class that saves tasks to todos.json and loads them on startup. Now your tasks survive program restarts
— a critical feature of any real app.
import json
from pathlib import Path
class JsonStorage:
"""Persist tasks to a JSON file."""
def __init__(self, path: str = "todos.json"):
self._path = Path(path)
def save(self, todo_list: TodoList) -> None:
"""Serialise all tasks to JSON file."""
data = []
for task in todo_list.all:
data.append({
"id": task.id,
"title": task.title,
"status": task.status.value,
"created_at": task.created_at,
"tags": task.tags,
})
with self._path.open("w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def load(self, todo_list: TodoList) -> int:
"""Load tasks from JSON into todo_list. Returns count loaded."""
if not self._path.exists():
return 0 # no file yet — that's OK
with self._path.open() as f:
data = json.load(f)
count = 0
for d in data:
task = Task(
title=d["title"],
id=d["id"],
created_at=d["created_at"],
tags=d.get("tags", []),
)
task.status = Status(d["status"])
todo_list._tasks.append(task)
count += 1
return count
# ── Persistent TodoList ────────────────────────────────
class PersistentTodoList(TodoList):
"""TodoList that auto-saves after every change."""
def __init__(self, path: str = "todos.json"):
super().__init__()
self._storage = JsonStorage(path)
loaded = self._storage.load(self)
print(f"📂 Loaded {loaded} tasks from {path}")
def _save(self): self._storage.save(self)
def add(self, *args, **kwargs) -> Task:
task = super().add(*args, **kwargs); self._save(); return task
def complete(self, task_id: str) -> Task:
task = super().complete(task_id); self._save(); return task
def delete(self, task_id: str) -> Task:
task = super().delete(task_id); self._save(); return task
# ── Usage ─────────────────────────────────────────────
todo = PersistentTodoList("my_todos.json")
t = todo.add("Write unit tests", tags=["dev"])
todo.add("Review pull request")
todo.complete(t.id)
# Tasks are saved to my_todos.json automatically!
# Next run: loaded automatically from file
Version 4 — Priority Levels & Due Dates
Add a Priority enum, due_date field, overdue detection, and sorting by priority and date. Tasks
become much more useful for real task management.
from enum import Enum, IntEnum
from datetime import datetime, date
class Priority(IntEnum):
"""IntEnum so priorities are sortable (LOW < MEDIUM < HIGH)."""
LOW = 1
MEDIUM = 2
HIGH = 3
URGENT = 4
@dataclass
class Task: # Extended Task with priority & due_date
title: str
status: Status = Status.TODO
priority: Priority = Priority.MEDIUM
due_date: str = "" # ISO format: "2025-12-31"
id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
tags: list[str] = field(default_factory=list)
def is_overdue(self) -> bool:
"""True if past due date and not completed."""
if not self.due_date or self.is_done(): return False
return date.fromisoformat(self.due_date) < date.today()
def days_until_due(self) -> int | None:
if not self.due_date: return None
delta = date.fromisoformat(self.due_date) - date.today()
return delta.days
def __str__(self) -> str:
icons = {Status.TODO: "⬜", Status.IN_PROGRESS: "🔄", Status.DONE: "✅"}
p_icons= {Priority.LOW: "🟢", Priority.MEDIUM: "🟡",
Priority.HIGH: "🔴", Priority.URGENT: "🚨"}
due = f" ⏰{self.due_date}" if self.due_date else ""
overdue= " ⚠️OVERDUE" if self.is_overdue() else ""
return f"{icons[self.status]} {p_icons[self.priority]} [{self.id}] {self.title}{due}{overdue}"
# ── Sorted display ────────────────────────────────────
class TodoList:
def sorted_by_priority(self) -> list[Task]:
return sorted(self._tasks, key=lambda t: -t.priority.value)
def overdue(self) -> list[Task]:
return [t for t in self._tasks if t.is_overdue()]
def due_today(self) -> list[Task]:
return [t for t in self._tasks
if t.due_date == date.today().isoformat() and not t.is_done()]
# ── Usage ─────────────────────────────────────────────
todo = TodoList()
todo.add("Submit assignment", due_date="2025-01-10", priority=Priority.URGENT)
todo.add("Read chapter 55", priority=Priority.HIGH)
todo.add("Reply to emails", priority=Priority.LOW)
for task in todo.sorted_by_priority(): print(task)
print(f"\n⚠️ Overdue: {len(todo.overdue())}")
Version 5 — Search, Filter & Sorting
Add full-text search, filter by status/priority/tag, multiple sort options, and an argparse-powered command-line interface for running the app with clean subcommands.
import argparse
# ── Search & filter methods on TodoList ───────────────
class TodoList:
def search(self, query: str) -> list[Task]:
"""Case-insensitive search in title and tags."""
q = query.lower()
return [
t for t in self._tasks
if q in t.title.lower()
or any(q in tag.lower() for tag in t.tags)
]
def filter_by_status(self, status: Status) -> list[Task]:
return [t for t in self._tasks if t.status == status]
def filter_by_priority(self, priority: Priority) -> list[Task]:
return [t for t in self._tasks if t.priority == priority]
def filter_by_tag(self, tag: str) -> list[Task]:
return [t for t in self._tasks if tag in t.tags]
def sorted_by(self, key: str = "created") -> list[Task]:
keys = {
"created": lambda t: t.created_at,
"priority": lambda t: -t.priority.value,
"due": lambda t: t.due_date or "9999",
"title": lambda t: t.title.lower(),
}
return sorted(self._tasks, key=keys.get(key, keys["created"]))
# ── argparse CLI ──────────────────────────────────────
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(prog="todo", description="📝 Python Todo App")
sub = p.add_subparsers(dest="command")
# add command
add = sub.add_parser("add", help="Add a new task")
add.add_argument("title", help="Task title")
add.add_argument("--priority", "-p", default="medium",
choices=["low","medium","high","urgent"])
add.add_argument("--due", "-d", help="Due date YYYY-MM-DD")
add.add_argument("--tags", "-t", nargs="*", default=[])
# list command
ls = sub.add_parser("list", help="List tasks")
ls.add_argument("--sort", choices=["created","priority","due","title"])
ls.add_argument("--filter", choices=["todo","done","overdue"])
# search command
sr = sub.add_parser("search", help="Search tasks")
sr.add_argument("query", help="Search term")
# done / delete commands
for cmd in ["done", "delete"]:
sp = sub.add_parser(cmd, help=f"{cmd.title()} a task")
sp.add_argument("id", help="Task ID")
return p
# Usage:
# python todo.py add "Buy groceries" --priority high --due 2025-06-01 --tags shopping
# python todo.py list --sort priority --filter todo
# python todo.py search "python"
# python todo.py done abc12345
Bonus — Rich Terminal UI with ANSI Colours
Make the CLI output beautiful with ANSI escape codes or the rich library — coloured priority badges, a table view, and a progress bar for
completion status.
# ── Option A: ANSI colour codes (no install needed) ───
class Colour:
RESET = "\033[0m"
BOLD = "\033[1m"
RED = "\033[91m"
YELLOW = "\033[93m"
GREEN = "\033[92m"
CYAN = "\033[96m"
GREY = "\033[90m"
WHITE = "\033[97m"
PRIORITY_COLOUR = {
Priority.LOW: Colour.GREEN,
Priority.MEDIUM: Colour.YELLOW,
Priority.HIGH: Colour.RED,
Priority.URGENT: f"{Colour.RED}{Colour.BOLD}",
}
def print_task(task: Task):
pc = PRIORITY_COLOUR[task.priority]
done = Colour.GREY if task.is_done() else ""
over = f"{Colour.RED} ⚠OVERDUE" if task.is_overdue() else ""
print(f" {done}{task.status.value:<12}"
f"{pc}{task.priority.name:<8}{Colour.RESET}"
f"{done}{task.title}{Colour.RESET}{over}")
def print_header():
print(f"\n{Colour.CYAN}{Colour.BOLD} 📝 Python Todo App{Colour.RESET}")
print(f"{Colour.GREY} {'─'*45}{Colour.RESET}")
print(f" {Colour.WHITE}{'Status':<14}{'Priority':<10}Title{Colour.RESET}")
print(f"{Colour.GREY} {'─'*45}{Colour.RESET}")
def print_progress(todo: TodoList):
stats = todo.stats()
pct = stats["done"] / stats["total"] if stats["total"] else 0
filled= int(pct * 20)
bar = "█" * filled + "░" * (20 - filled)
print(f"\n Progress: {Colour.GREEN}[{bar}]{Colour.RESET} "
f"{stats['done']}/{stats['total']} ({stats['pct']})\n")
# ── Option B: rich library (pip install rich) ─────────
# from rich.console import Console
# from rich.table import Table
# console = Console()
# table = Table("ID", "Status", "Priority", "Title", "Due")
# for task in todo.all:
# table.add_row(task.id, task.status.value,
# task.priority.name, task.title, task.due_date)
# console.print(table)
# ── Demo output ───────────────────────────────────────
todo = TodoList()
todo.add("Deploy to production", priority=Priority.URGENT, due_date="2025-06-01")
todo.add("Write unit tests", priority=Priority.HIGH)
todo.add("Update documentation", priority=Priority.MEDIUM)
t = todo.add("Review PRs", priority=Priority.LOW)
todo.complete(t.id)
print_header()
for task in todo.sorted_by_priority(): print_task(task)
print_progress(todo)
Practice Python Online — Free Compilers
Run and test all Todo App versions in your browser. v1–v4 work in any online compiler. For v5 with argparse and file persistence, use Replit or a local Python environment.
- v1 (Functions): A list of task dicts, CRUD functions, a while-loop menu parser. Tasks stored in memory — lost on exit. Introduces the core app structure.
- v2 (OOP):
Taskdataclass withStatusenum,TodoListmanager class, UUID-based IDs, tags, custom exceptions, and statistics viastats(). - v3 (Persistence):
JsonStorageclass serialises/deserialises tasks totodos.json.PersistentTodoListinherits fromTodoListand auto-saves on every mutation. - v4 (Priority & Dates):
Priority(IntEnum)makes priorities sortable.due_datefield with overdue detection viadate.fromisoformat(). Sort and filter methods added. - v5 (Search & CLI): Full-text search across title and tags. Filter by status,
priority, tag. Multiple sort keys.
argparsesubcommands:add,list,done,delete,search. - Bonus (Rich UI): ANSI colour codes for coloured terminal output (no install required).
Priority-coded colours, progress bar. Optionally use the
richlibrary for a beautiful table view. - Architecture pattern:
Task→TodoList→JsonStorage→ CLI. Separating data model from storage from UI is the foundation of clean software design. - Extend the app: add categories, recurring tasks, export to CSV, share via REST API (requests, Ch 52), or build a web frontend with Flask/Django.
A @dataclass provides several advantages over a plain dict:
- Named access:
task.titleinstead oftask["title"]— no typos at runtime - Type hints: fields have declared types, IDEs and type checkers catch errors
- Default values:
field(default_factory=...)for complex defaults - Auto __repr__ and __eq__: generated automatically
- Methods: can add
complete(),is_overdue(),__str__— can't do this on a dict
IntEnum members are both an enum AND an integer, which makes them
directly sortable with Python's sorted():
Priority.LOW = 1
Priority.MEDIUM = 2
Priority.HIGH = 3
Priority.URGENT = 4
# sortable directly:
Priority.LOW < Priority.HIGH # True
# sort tasks highest priority first:
sorted(tasks, key=lambda t: -t.priority)
A regular Enum with string values like
"high" can't be compared with < or >.
Inheritance (IS-A relationship) is appropriate here because PersistentTodoList IS a TodoList —
it has all the same operations plus auto-save behaviour. This is the extension
pattern:
- All
TodoListmethods work onPersistentTodoList - Only
add(),complete(),delete()are overridden to add auto-save - The override calls
super().method()so no logic is duplicated
The search uses a list comprehension that checks if the lowercase query appears in the lowercased title OR any tag:
q = query.lower() # lowercase query once
[t for t in tasks
if q in t.title.lower() # check title
or any(q in tag.lower() for tag in t.tags)]
Converting both sides to .lower() makes
the search case-insensitive — "PYTHON" matches "python", "Python", "PYTHON" all equally.
Strong portfolio extensions:
- Sub-tasks — add a
subtasks: list[Task]field to Task. A parent task is only complete when all sub-tasks are done. Demonstrates recursive data structures. - REST API — expose the todo list via a FastAPI/Flask endpoint. Each CRUD operation maps to a HTTP method (GET /tasks, POST /tasks, PATCH /tasks/{id}, DELETE /tasks/{id}). Connects to Ch 52.
- Recurring tasks — add a
recurrencefield ("daily", "weekly", "monthly"). When you complete a recurring task, automatically create the next occurrence. Demonstrates datetime arithmetic.
@dataclass decorator automatically generates
which methods?add_subparsers(dest="command") create?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.