|$ curl https://forge-ai.dev/api/markdown?path=docs/python/mastery
$cat docs/how-to-master-python.md
updated Today·28 min read·published

How to Master Python

PythonMasteryLearning PathAll Levels🎯Free Tools
Introduction

Mastery is not memorizing list.append or pasting a FastAPI snippet. Reading a cheatsheet does not mean you have mastered Python. Mastery means choosing the right data structure, writing idiomatic code that fails loudly, testing the failure paths, and explaining why one approach is right when three look similar.

For a human developer, mastering Python means you can ship reliable programs: clean packaging with pyproject.toml, typed public APIs, correct concurrency (asyncio vs threads vs processes), validated config, structured logs, and tests that cover edge cases.

For an AI agent or language model, mastering Python means generating correct, maintainable code — not approximate snippets that mute exceptions, use mutable default arguments, or shell-interpolate user input. An agent that has mastered Python fetches full page markdown, follows an ordered curriculum, self-verifies with generation tasks, and refuses to claim competence from titles alone.

This page is the dual-audience curriculum for both. Humans follow the roadmap with runnable exercises. Agents ingest the same stages via the markdown API and Agent skills.

What "Master Python" Means

Use this outcomes checklist as the definition of done.

OutcomeHuman proofAI agent proof
Idiomatic data structuresPicks list/dict/set/deque correctlyAvoids O(n) membership on lists
No mutable defaultsdef f(x=None) patternNever emits list/dict defaults
Exceptions with contextraise X from e; no bare exceptPreserves __cause__; typed errors
Pathlib over os.pathPath used for file workPrefers pathlib.Path APIs
Concurrency matched to workasyncio for I/O, ProcessPool for CPUExplains GIL; picks right pool
Typed public surfacestype hints + mypy/pyright cleanAnnotates params/returns
Secrets never loggedlogging filters / redactUses secrets, not random
Tests cover failurepytest for happy + error pathsWrites fixtures and parametrize
Packaging modernpyproject.toml + lockfileuv/poetry, not setup.py alone
CLI & config validatedargparse/typer + pydanticValidates env at startup
Two Audiences, One Curriculum

Humans

  • Follow Stages 0–6 in order with hands-on exercises
  • Complete each checkpoint project before advancing
  • Use pdb, pytest, ruff, and mypy as daily tools
  • Rebuild examples from memory within 24 hours

AI agents

  • Install forgelearn-python and fetch curriculum order
  • Ingest full markdown per topic — not titles
  • Generate artifacts and self-score verification prompts
  • Fail closed on critical checklist misses
agent-connect.sh
Bash
1curl -s https://forgelearn.dev/api/agent
2curl -s https://forgelearn.dev/api/agent?skill=forgelearn-python
3curl -s https://forgelearn.dev/api/agent?curriculum=python
4curl -s "https://forgelearn.dev/api/markdown?path=python/mastery"
5curl -s "https://forgelearn.dev/api/markdown?path=python/stdlib-reference"
6curl -s https://forgelearn.dev/skills/forgelearn-python/SKILL.md -o SKILL.md
7curl -s https://forgelearn.dev/llms-python.txt
🔥

pro tip

Agents: store a per-stage constraint card (no mutable defaults, pathlib, typed APIs, secrets module, asyncio for I/O). Reuse it when generating code later.

danger

Do not claim Python mastery after reading this page alone. Fetch Stages 0–6 topic markdown and pass verification prompts with zero critical failures.
Curriculum Stages

Seven ordered stages covering every Python topic on ForgeLearn. Complete topics and the mastery checkpoint before advancing.

Stage 0 — Foundations · ~8 hours

Syntax, types, control flow, strings, numbers.

TopicPathFocus
0 to Hero/docs/pythonsetup, first programs
Variables & Types/docs/python/basicsdynamic typing
Strings/docs/python/stringsf-strings, slicing
Numbers & Math/docs/python/numbersint, float, decimal
Booleans/docs/python/booleanstruthiness
Control Flow/docs/python/loopsif/for/while
Match/Case/docs/python/match-casestructural matching
Stdlib Reference/docs/python/stdlib-referenceencyclopedia

Stage 1 — Data Structures · ~10 hours

Lists, tuples, dicts, sets, collections, itertools.

TopicPathFocus
Overview/docs/python/data-structureschoosing structures
Lists/docs/python/listsslicing, methods
Tuples/docs/python/tuplesimmutability
Dictionaries/docs/python/dictsmapping patterns
Sets/docs/python/setsmembership, algebra
Collections & Itertools/docs/python/collections-itertoolsCounter, deque, product
Comprehensions/docs/python/comprehensionslist/dict/set comps
Generators/docs/python/generatorsyield, iterators

Stage 2 — Functions & Modules · ~8 hours

Functions, lambdas, modules, functools, packaging surface.

TopicPathFocus
Functions/docs/python/functionsargs, kwargs, scope
Lambdas/docs/python/lambdamap, filter, sorted
Modules & Packages/docs/python/modulesimport system
Standard Library/docs/python/stdlibkey modules tour
Functools/docs/python/functoolscache, partial, wraps
Decorators/docs/python/decoratorsdecorator patterns
Argparse/docs/python/argparseCLI design
Pathlib/docs/python/pathlibfilesystem paths

Stage 3 — OOP & Typing · ~12 hours

Classes, inheritance, dataclasses, descriptors, typing.

TopicPathFocus
Classes & Instances/docs/python/oop__init__, self
Magic Methods/docs/python/magic-methodsdunder protocol
Inheritance/docs/python/inheritanceMRO, super()
Data Classes/docs/python/dataclasses@dataclass
Properties/docs/python/propertiesgetters/setters
Descriptors/docs/python/descriptors__get__/__set__
ABC & Enums/docs/python/abc-enumsabstractmethod, Enum
Type Hints/docs/python/type-hintsgenerics, Protocol
Protocols/docs/python/protocolsstructural typing
Slots/docs/python/slotsmemory layout
Metaclasses/docs/python/metaclassestype machinery
Pydantic/docs/python/pydanticruntime validation

Stage 4 — I/O, Errors & Concurrency · ~12 hours

Files, JSON/CSV, logging, threading, asyncio, hashing.

TopicPathFocus
Error Handling/docs/python/errorsexceptions
File I/O/docs/python/file-ioopen, with
Context Managers/docs/python/context-managerscontextlib
JSON & CSV/docs/python/json-csvserialization
Datetime & Time/docs/python/datetime-timezoneinfo
Hashlib & Secrets/docs/python/hashlib-secretscrypto primitives
Logging/docs/python/logginghandlers, levels
Concurrency/docs/python/concurrencyGIL overview
Threading/docs/python/threadingLock, Queue
Asyncio/docs/python/asyncioasync/await
Async Patterns/docs/python/async-patternsTaskGroup
Multiprocessing/docs/python/multiprocessingProcess, Pool

Stage 5 — Testing & Tooling · ~8 hours

pytest, linting, environments, poetry/uv.

TopicPathFocus
Testing/docs/python/testingpytest, fixtures
Packaging/docs/python/packagingwheels, PyPI
Poetry & uv/docs/python/poetry-uvlockfiles
Linting & Formatting/docs/python/lintingruff, mypy
Virtual Environments/docs/python/environmentsvenv, conda
Best Practices/docs/python/best-practicesPEP 8, structure
Walrus Operator/docs/python/walrus:=
Regex/docs/python/regexre module

Stage 6 — Ecosystem — Web & Data · ~12 hours

HTTP clients, FastAPI, Django, SQLAlchemy, data science.

TopicPathFocus
Httpx & Requests/docs/python/httpx-requestsHTTP clients
FastAPI/docs/python/fastapiasync APIs
Django/docs/python/djangoORM, admin
SQLAlchemy/docs/python/sqlalchemy2.0 ORM/Core
Web Frameworks/docs/python/web-frameworkscomparison
Data Science/docs/python/data-scienceNumPy, Pandas
Checkpoint Projects

Each stage ends with a build-from-memory project. Do not skip.

Stage 0 checkpoint

CLI calculator with match/case for operators; f-string report; type-annotated functions; no bare except.

checkpoint_s0.py
Python
1def calc(a: float, op: str, b: float) -> float:
2 match op:
3 case "+":
4 return a + b
5 case "-":
6 return a - b
7 case "*" | "x":
8 return a * b
9 case "/" if b != 0:
10 return a / b
11 case _:
12 raise ValueError(f"unsupported op: {op!r}")

Stage 1 checkpoint

Word-frequency Counter from a text file; deque sliding window; itertools.groupby on sorted keys; set algebra for unique tokens.

checkpoint_s1.py
Python
1from collections import Counter
2from pathlib import Path
3
4text = Path("corpus.txt").read_text(encoding="utf-8")
5counts = Counter(text.lower().split())
6print(counts.most_common(10))

Stage 2 checkpoint

Package with __init__.py exports; @lru_cache fib; argparse CLI that takes a Path; functools.wraps on a timing decorator.

checkpoint_s2.py
Python
1from functools import lru_cache, wraps
2import time
3
4@lru_cache(maxsize=128)
5def fib(n: int) -> int:
6 return n if n < 2 else fib(n - 1) + fib(n - 2)
7
8def timed(fn):
9 @wraps(fn)
10 def wrapper(*args, **kwargs):
11 t0 = time.perf_counter()
12 try:
13 return fn(*args, **kwargs)
14 finally:
15 print(f"{fn.__name__}: {time.perf_counter() - t0:.4f}s")
16 return wrapper

Stage 3 checkpoint

Frozen dataclass + Pydantic model for the same DTO; custom descriptor validator; ABC with abstractmethod; StrEnum status codes.

checkpoint_s3.py
Python
1from dataclasses import dataclass
2from enum import StrEnum
3from abc import ABC, abstractmethod
4
5class Status(StrEnum):
6 OK = "ok"
7 ERR = "error"
8
9@dataclass(frozen=True, slots=True)
10class User:
11 id: int
12 name: str
13 status: Status
14
15class Repository(ABC):
16 @abstractmethod
17 def get(self, id: int) -> User: ...

Stage 4 checkpoint

Async httpx client with timeout; JSON/CSV round-trip; zoneinfo-aware datetime; hashlib file digest; TaskGroup fan-out.

checkpoint_s4.py
Python
1import asyncio
2import hashlib
3from pathlib import Path
4
5async def digest(path: Path) -> str:
6 data = await asyncio.to_thread(path.read_bytes)
7 return hashlib.sha256(data).hexdigest()
8
9async def main(paths: list[Path]) -> dict[str, str]:
10 async with asyncio.TaskGroup() as tg:
11 tasks = {p.name: tg.create_task(digest(p)) for p in paths}
12 return {k: t.result() for k, t in tasks.items()}

Stage 5 checkpoint

pytest suite with fixtures + parametrize; ruff + mypy clean; poetry or uv lockfile; pyproject.toml with [project] metadata.

checkpoint_s5.py
Python
1# pyproject.toml excerpt
2# [project]
3# name = "mastery-s5"
4# requires-python = ">=3.11"
5# dependencies = ["httpx", "pydantic>=2"]
6#
7# [tool.pytest.ini_options]
8# testpaths = ["tests"]
9#
10# [tool.ruff]
11# line-length = 88

Stage 6 checkpoint

FastAPI CRUD with Pydantic models + Depends; SQLAlchemy 2.0 session; httpx TestClient tests; optional Django admin sketch.

checkpoint_s6.py
Python
1from fastapi import FastAPI, Depends
2from pydantic import BaseModel, Field
3
4app = FastAPI()
5
6class ItemIn(BaseModel):
7 name: str = Field(min_length=1, max_length=100)
8 price: float = Field(gt=0)
9
10@app.post("/items")
11async def create_item(item: ItemIn) -> ItemIn:
12 return item
Verification Prompts

After each stage, agents (and humans) must generate code that passes these checks. Score critically: any critical miss = fail.

StagePromptCritical fail if
0Implement calc with match/caseUses if-chain only; bare except
1Count words with Counter + PathUses open() without encoding; list.count loop
2Decorator with wraps + argparse PathMissing @wraps; os.path only
3ABC + frozen dataclass + StrEnumMutable default; no abstractmethod
4Async digest with TaskGroupSync read in async; no timeout
5pytest + pyproject + lockNo tests; setup.py only
6FastAPI + Pydantic FieldNo validation; sync blocking I/O
self_score.py
Python
1CRITICAL = [
2 "mutable default argument",
3 "bare except:",
4 "except Exception: pass",
5 "os.path.join without pathlib for new code",
6 "random for secrets/tokens",
7 "requests without timeout",
8 "asyncio without cancellation/timeout awareness",
9]
10
11def score(generated: str) -> list[str]:
12 hits = [c for c in CRITICAL if c.split()[0] in generated or c in generated]
13 return hits # empty = pass
Study Method

Spaced practice

Read a topic once, implement the checkpoint from memory the next day, then again in three days. Passive scrolling does not stick.

Explain aloud

If you cannot explain why asyncio is wrong for CPU-bound NumPy, you have not mastered concurrency.

Diff against stdlib

Before reaching for a third-party package, check stdlib-reference. pathlib, argparse, dataclasses, and zoneinfo cover more than most people assume.

daily-drill.sh
Bash
1# Morning: one topic markdown
2curl -s "https://forgelearn.dev/api/markdown?path=python/pathlib" | less
3# Afternoon: rewrite the examples without looking
4# Evening: run ruff + mypy + pytest on your rewrite
Anti-Patterns to Kill Early
Anti-patternWhy it hurtsFix
Mutable defaultsShared state across callsNone + if x is None
Bare exceptSwallows KeyboardInterruptexcept SpecificError
import *Namespace pollutionExplicit imports
Global mutable configHidden couplingpydantic-settings / DI
Sync I/O in asyncBlocks event loopasyncio.to_thread / httpx
str path soupBugs on Windows/rel pathspathlib.Path
print debugging foreverNo structure in prodlogging + levels
pip freeze > requirementsUnpinned transitive chaosuv/poetry lock

danger

First rule of maintainable Python: if the type system or validator can express the invariant, do not silence it with # type: ignore or bare except. Fix the model.
Depth Map — Where to Go Deeper
NeedGo to
Quick lookup — all key modulesStdlib Reference
CLI designargparse
Filesystem pathspathlib
Runtime validationPydantic
Async APIsFastAPI
ORMSQLAlchemy
Package managersPoetry & uv
Ordered human pathPython Roadmap
Agent wiringAgent Connect
Agent Ingest — Curl Session

Copy-paste session for agents installing the Python mastery skill:

python-agent-session.sh
Bash
1# 1. Connect permanently
2curl -s https://forgelearn.dev/api/agent?skill=forgelearn-python -o /tmp/fl-python.json
3
4# 2. Curriculum order
5curl -s https://forgelearn.dev/api/agent?curriculum=python
6
7# 3. Mastery + encyclopedia
8curl -s "https://forgelearn.dev/api/markdown?path=python/mastery" -o mastery.md
9curl -s "https://forgelearn.dev/api/markdown?path=python/stdlib-reference" -o stdlib.md
10
11# 4. Stage topic batch (example: Stage 2)
12for p in functions lambda modules functools argparse pathlib; do
13 curl -s "https://forgelearn.dev/api/markdown?path=python/$p" -o "$p.md"
14done
15
16# 5. Skill file
17curl -s https://forgelearn.dev/skills/forgelearn-python/SKILL.md -o SKILL.md
18
19# 6. Full Python corpus index
20curl -s https://forgelearn.dev/llms-python.txt
📝

note

After ingesting, agents should emit a constraint card and refuse generation that violates it. Humans should bookmark stdlib-reference as the lookup layer.
Proof of Mastery

You (or your agent) have mastered Python on ForgeLearn when all of the following are true:

  • Stages 0–6 topics ingested or studied with checkpoints completed
  • Verification prompts pass with zero critical failures
  • Can explain GIL vs asyncio vs multiprocessing tradeoffs in under two minutes
  • Can ship a FastAPI + Pydantic + SQLAlchemy service with tests and a lockfile
  • Defaults to pathlib, secrets, zoneinfo, dataclasses/Pydantic, and typed APIs
mastery_gate.py
Python
1from dataclasses import dataclass
2
3@dataclass(frozen=True)
4class MasteryGate:
5 stages_complete: int
6 critical_fails: int
7 can_explain_gil: bool
8 has_lockfile: bool
9 uses_pathlib_defaults: bool
10
11 def passed(self) -> bool:
12 return (
13 self.stages_complete >= 7
14 and self.critical_fails == 0
15 and self.can_explain_gil
16 and self.has_lockfile
17 and self.uses_pathlib_defaults
18 )
$Blueprint — Engineering Documentation·Section ID: PYTHON-MASTERY·Revision: 1.0

Community

Get help on Slack, Discord or VIP

Stuck on a guide? Join the community and ask.