Python programs operate on objects with explicit input, ownership and failure contracts.
Learning roadmap
This section contains 39 written lessons or quiz banks. Programs are verified on CPython 3.14.6. Standard-library lessons target 3.11+ syntax; lessons using data, web, machine-learning or testing packages state their tested dependencies separately. Framework programs use local test clients, not a deployed service. Read the stated limits before adapting a fixture into an application.
Interpreter and values
Read the contract, run its program and inspect the failure case.
- Python interpreter and virtual environments: run the intended executable
- Python variables: names refer to objects, assignment does not copy
- Python numeric operators: division, floor division and remainder contracts
- Python conditions and loops: distinguish no value from an empty value
- Python match statements: shape matching is not input validation
Functions and failures
Read the contract, run its program and inspect the failure case.
- Python functions: define units, validate input and return a result
- Python function arguments: avoid shared mutable defaults
- Python exceptions: translate an input error without hiding its cause
- Python modules: separate import-time definitions from program execution
- Python string formatting: format text without building SQL syntax
- Python type hints: annotations do not enforce runtime arguments
Sequence expressions
Read the contract, run its program and inspect the failure case.
- Python comprehensions: build results without changing the input
- Python list slicing: half-open ranges and shallow ownership
Object state
Read the contract, run its program and inspect the failure case.
- Python classes: keep instance state separate from class state
- Python inheritance: override behavior without inventing shared ownership
- Python properties: validate mutation at the public attribute boundary
Scope and call boundaries
Read the contract, run its program and inspect the failure case.
- Python scope: local assignment, nonlocal state and late binding
- Python unpacking: keyword collisions and strict record pairing
Bounded nested input
Read the contract, run its program and inspect the failure case.
Input, iteration and function tools
Read the contract, run its program and inspect the failure case.
- Python input and output: separate parsing from terminal I/O
- Python truth values: distinguish missing data from valid zero
- Python type conversion: parsing success is not field validity
- Python break, continue and loop else: encode the stopping condition
- Python range and enumerate: indexes are not stable record identities
- Python lambda functions: one expression and the same closure rules
- Python map, filter and reduce: iterator timing and reduction identity
- Python staticmethod and classmethod: choose the bound receiver
Source names, callable dispatch and preserved startup contracts
Read the contract, run its program and inspect the failure case.
- Python keywords and identifiers: parser rules differ from field rules
- Python first-class functions: dispatch through an explicit operation registry
- Python refactoring: preserve rejected inputs as well as accepted results
- Python import failures: module removal does not roll back every side effect
Stable rejection and explicit calls
Read the contract, run its program and inspect the failure case.
- Python assert versus input validation: optimized execution changes the contract
- Python positional-only and keyword-only parameters: keep call roles explicit
Unpacking and evaluation
Read the contract, run its program and inspect the failure case.
- Python starred unpacking: allocate the middle and reject wrong arity
- Python comparison chains: the middle operand is evaluated once
- Python module cache: repeated imports reuse an owned module object
- Python assignment expressions: capture a checked value once
Pull loops and sentinels
Read the contract, run its program and inspect the failure case.
Strictly paired feeds
Read the contract, run its program and inspect the failure case.
Continue learning
Move between tutorial, collections, advanced material and practice using the subject tabs. The sidebar changes with each section; related examples keep one canonical lesson URL.
- Data Types & Collections
- Advanced Python
- Interview Questions
- Exercises
- Examples
- Quizzes
- Projects
- Cheatsheet
- DSA in Python
- Packaging & Tools
- Data Analysis
- Web Applications
- Testing & Quality
Runtime and integrity contracts
- Python asyncio Semaphore: bound active work, not queued tasks
- Python Future cancellation: queued work versus running work
- Python Queue task_done: completion accounting includes shutdown items
- Python SQLite busy writer: handle contention as a bounded outcome
- Python SQLite WAL reader: an open transaction keeps its snapshot
- Python JSON nonfinite numbers: reject NaN on input and output
- Python heapq priority updates: skip stale entries
- Python topological failure: return a cycle witness
- Python interval capacity sweep: process ends before starts
- Python frozen dataclass: field rebinding stops, nested mutation remains
Export, network and command contracts
- Python CSV export: spreadsheet cells are an execution boundary
- Python ipaddress membership: parse the peer before an allowlist
- Python argparse subcommands: require the operation before side effects
Test this contract in the Python concurrency and storage boundary quiz.
Test this contract in the Python I/O and algorithm boundary quiz.
Process and data contracts
- Python subprocess timeout: kill and reap the timed-out child
- Python subprocess output: spool bytes before accepting a report
- Python TLS client context: require certificate and hostname checks
- Python SQLite migration: commit schema and version as one unit
- Python JSON duplicate names: reject ambiguous object fields
- Python tar preflight: reject links and path escapes before extraction
- Python generated checks: name the invariant and keep rejected cases
- Python file replacement: write a sibling file before changing the name
Check the process and data boundary quiz.
Lifetime and I/O contracts
- Python multiprocessing spawn: keep startup behind the main guard
- Python ContextVar tasks: capture request context at task creation
- Python weak-value cache: an entry does not own its result
- Python SQLite migration: reopen the file after a failed upgrade
- Python tar extraction: reject members before exceeding a byte quota
- Python subprocess pipe: stop after the first byte beyond budget
- Python socket idle timeout: bound one blocking receive
- Python streaming SHA-256: hash bytes without a second full copy
Check the lifetime and I/O quiz.
Python 3.13 and 3.14 library contracts
- Python Queue.shutdown: drain accepted work before workers exit
- Python batched strict: reject an incomplete import group
- Python copy.replace: revise one field without cloning owned data
- Python UUIDv7: time-ordered IDs without treating them as a clock
- Python deferred annotations: inspect forward names without resolving them
- Python Zstandard decompression: stop at an output budget
- Python Executor.map buffersize: pause submission when results wait
- Python heapq max-heap: keep highest-priority scores at the root
Check the versioned runtime quiz.
Runtime and observability contracts
- Python free-threaded builds: lock the whole shared-state update
- Python InterpreterPoolExecutor: pass results across isolated runtimes
- Python template strings: escape text values before rendering HTML
- Python cProfile: inspect call counts without asserting timing
- Python asyncio call graphs: inspect a live task without retaining frames
- Python ctypes.memoryview_at: keep native pointer storage alive
- Python partial Placeholder: leave a positional amount open
- Python Path.copy: a snapshot needs an explicit metadata policy
Check the runtime and observability quiz.
Native and platform boundaries
- Python C extension: compile, import, and reject bad input
- Python Limited API: build an abi3 extension without claiming a full release matrix
- Python free-threaded diagnostics: separate build capability from current GIL state
- Python signal handlers: install from the main interpreter thread
- Python POSIX filename bytes: round-trip an undecodable path
- Python POSIX subprocess timeout: stop the owned process group
- Python amount parsing: define a wire format before Decimal
- Python audit hooks: observe an owned file open without claiming a sandbox
Check the native and platform quiz.
Bounded streams and storage controls
- Python asyncio byte frames: reject an oversized length before reading a body
- Python asyncio delimiter limits: an overrun leaves the bytes buffered
- Python SQLite blob handles: preallocate bytes and keep the write inside a transaction
- Python SQLite authorizer: deny a statement on the connection that executes it
- Python SQLite progress handler: interrupt one expensive statement
- Python SQLite SQL length limits: cap statement text separately from bound values
- Python mmap access modes: write-through changes a file, copy-on-write does not
- Python os.scandir metadata: a cached DirEntry is not a fresh file check
- Python SQLite Row: duplicate result names make named access ambiguous
Check the stream and storage quiz.
Received data and owned local I/O
- Python pickle: preserve trusted aliases without decoding received objects
- Python query strings: retain blank fields and reject repeated keys
- Python EmailMessage: keep received newlines out of a header field
- Python email parsing: inspect all sender headers before trusting one
- Python ConfigParser: read literal percent signs without hidden interpolation
- Python socket recv: assemble an exact frame across local socket reads
- Python TextIOWrapper: choose whether input line endings are normalized
- Python POSIX dir_fd and O_NOFOLLOW: reject a final symlink on an owned open
Check the received-input quiz.
Cross-thread scheduling and cleanup lifetime
- Python AsyncExitStack: unwind acquired resources after a later open fails
- Python asyncio loop callbacks: submit from a worker with call_soon_threadsafe
- Python thread-local state: a reused pool worker retains the previous job's value
- Python eager asyncio tasks: a coroutine can finish before create_task returns
- Python weakref.finalize: run an idempotent cleanup callback once
- Python RLock: permit nested ledger methods without dropping the outer lock
- Python run_coroutine_threadsafe: submit to a live loop and own shutdown
- Python asyncio.to_thread cancellation: the blocking worker can outlive its awaiter
Check the thread and async lifetime quiz.
Standard-library state and ownership contracts
- Python ContextVar tokens: restore nested request state exactly
- Python itertools.groupby: contiguous runs are not global groups
- Python bounded deque: append silently evicts the opposite end
- Python dataclass InitVar: validate and derive state without storing input
- Python SQLite row factories: reject duplicate output names before mapping
- Python QueueListener: stop the logging worker after queued records drain
- Python threading.Barrier: abort a failed phase so peers do not wait forever
- Python decimal localcontext: keep a rounding rule inside one calculation
- Python bisect key: search with a key value, insert with a record
- Python lru_cache: callers share the same cached mutable result
