Reading Mode
CH 14·Lesson 1
Phase 1 — Python Foundation — Checkpoint Answer Guide
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
advanced11 min read
Learning Objectives
- Python Basics
- OOP in Python
- Advanced Python
- Python Ecosystem
- CAPSTONE: Personal Finance Tracker CLI
This is a grading guide, not a script to memorize. Equivalent designs earn credit when their assumptions and evidence are correct.
Python Basics
- Variables & data types: Python's core scalar values include arbitrary-precision integers, binary64 floating-point numbers, immutable Unicode strings, booleans, and the singleton
None. A strong answer also explains that every value is an object with a type and identity.boolis a subclass ofint;floatfollows IEEE-754 behavior such as rounding and NaN;strstores Unicode and creates a new string for transformations;Nonerepresents absence, not zero or an empty string. The main warning is: Truthiness can collapse distinct states:0,'', empty containers, andNoneare all falsey but do not mean the same thing. - Control flow: Conditional statements execute exactly one matching branch in source order, with an optional fallback branch. A strong answer also explains that cPython evaluates each condition and applies truth-value testing (
__bool__, then__len__where applicable). Short-circuitandandorstop as soon as the result is known and return an operand, not necessarily a boolean. The main warning is: Deep nesting and mixedand/orexpressions without parentheses hide precedence and missed cases. - Functions & scope: A function packages a call contract with positional, keyword, variadic, defaulted, and return behavior. A strong answer also explains that a function object is created when
defexecutes. Default expressions are evaluated once at definition time. Each call creates a frame, binds arguments, and returnsNonewhen execution reaches the end withoutreturn. The main warning is: A mutable default such asitems=[]is shared by every call and accumulates state. - Comprehensions: A list comprehension maps and optionally filters an iterable into a newly allocated list. A strong answer also explains that its loop variable has comprehension-local scope in Python 3. The whole result list is retained; evaluation is eager and ordered. The main warning is: Side effects, nested conditions, or expensive repeated expressions make a comprehension harder to understand than a loop.
- String formatting: An f-string evaluates embedded Python expressions and formats their values using each type's
__format__protocol. A strong answer also explains that the compiler builds formatting bytecode; width, alignment, precision, numeric grouping, and datetime specifiers are delegated to the value type. The main warning is: Formatting is presentation, not localization or SQL/shell escaping; never treat it as an injection defense. - Complete string method reference: Case-conversion methods return new Unicode strings;
casefoldis the aggressive normalization intended for caseless comparison, while lower/upper/title/capitalize are presentation transformations. A strong answer also explains that unicode case mapping is not always one input code point to one output code point. Casefold can expand characters, so normalized text length and byte encoding may change. The main warning is: Do not uselower()as a universal international identifier or authorization normalization rule without a specified Unicode policy.
OOP in Python
- Classes & objects: Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. A strong answer also explains that attribute lookup walks the instance, its class, and the class MRO.
super()follows that computed MRO, enabling cooperative multiple inheritance when signatures agree. The main warning is: Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. - Inheritance & polymorphism: Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. A strong answer also explains that attribute lookup walks the instance, its class, and the class MRO.
super()follows that computed MRO, enabling cooperative multiple inheritance when signatures agree. The main warning is: Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling. - Dunder methods: Container dunder methods let an object participate in built-in length, indexing, slicing, iteration fallback, and assignment syntax. A strong answer also explains that
lenrequires a non-negative integer from__len__; subscription passes an integer, slice, or other key to__getitem__; assignment dispatches to__setitem__. The main warning is: Surprising side effects or inconsistent negative-index/slice behavior violates users' expectations of a Python container. - Dataclasses: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. A strong answer also explains that decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references.
wrapspreserves metadata and the wrapped chain. The main warning is: Keep retries bounded and restricted to transient, idempotent operations. - Abstract Base Classes: Python objects combine identity, state, and behavior; inheritance and protocols define substitution relationships. A strong answer also explains that attribute lookup walks the instance, its class, and the class MRO.
super()follows that computed MRO, enabling cooperative multiple inheritance when signatures agree. The main warning is: Direct parent calls break cooperative MRO and deep hierarchies create fragile coupling.
Advanced Python
- Generators & iterators: An iterator produces one item at a time; a generator is an iterator whose suspended function frame resumes around
yield. A strong answer also explains thatiter()obtains an iterator and repeatednext()calls either yield a value or raiseStopIteration. A generator preserves its instruction pointer, locals, and exception state. The main warning is: A consumed iterator is exhausted; converting it to a list defeats streaming and may exhaust memory. - Decorators: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. A strong answer also explains that decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references.
wrapspreserves metadata and the wrapped chain. The main warning is: Keep retries bounded and restricted to transient, idempotent operations. - Context managers: A context manager brackets a block with deterministic setup and cleanup. A strong answer also explains that the
withstatement calls__enter__, runs the body, then calls__exit__even during stack unwinding.__exit__can suppress an exception only by returning truthy. The main warning is: Do not hide unexpected exceptions in__exit__; cleanup should be exception-safe. - Type hints & mypy: Type hints describe intended value relationships for tools without changing ordinary Python runtime dispatch. A strong answer also explains that a static checker builds a type model from annotations; generics preserve a relationship such as input and output element type. Runtime validation requires a separate library. The main warning is:
Optional[T]meansT | None; it does not mean an optional function parameter. - asyncio basics: Cooperative concurrency lets one task yield while it waits so another ready task can use the same thread. A strong answer also explains that calling an async function creates a coroutine.
awaitsuspends only at an awaitable; the event loop schedules callbacks and resumes ready tasks.gatherpreserves input order but failure policy must be chosen. The main warning is: A blocking library call freezes the loop; move unavoidable sync work to a bounded executor. - Composition & performance: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. A strong answer also explains that decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references.
wrapspreserves metadata and the wrapped chain. The main warning is: Keep retries bounded and restricted to transient, idempotent operations.
Python Ecosystem
- pip & virtual environments: Environment and dependency tools isolate packages and record the inputs needed to reproduce an installation. A strong answer also explains that a virtual environment changes interpreter and script paths; resolvers choose compatible distributions; a lock or compiled requirements file records exact transitive versions. The main warning is:
pip freezecaptures the current environment, including accidental packages; it is not always a clean dependency design. - Poetry & Pipenv: Environment and dependency tools isolate packages and record the inputs needed to reproduce an installation. A strong answer also explains that a virtual environment changes interpreter and script paths; resolvers choose compatible distributions; a lock or compiled requirements file records exact transitive versions. The main warning is:
pip freezecaptures the current environment, including accidental packages; it is not always a clean dependency design. - Testing with pytest: Automated tests arrange state, exercise one behavior, and assert observable outcomes; pytest fixtures model reusable setup as a dependency graph. A strong answer also explains that fixture scope controls lifetime and caching. Parametrization creates independent cases. Mocks replace the name used by the code under test, not necessarily the original definition. The main warning is: Coverage measures execution, not correctness; patching the wrong import path produces deceptive tests.
- Logging: Logging emits structured, leveled operational events to one or more destinations. A strong answer also explains that a logger creates a record; filters and handlers decide routing; formatters serialize it. Correlation identifiers connect events belonging to one request or workflow. The main warning is: Do not use logs as the only audit store or interpolate expensive messages before level checks.
- argparse & CLI tools: A CLI parser converts process arguments into validated commands and options. A strong answer also explains that the shell tokenizes a command line first; the parser then applies positional/optional rules and dispatches to a handler. The main warning is: Return meaningful exit codes and write diagnostics to stderr.
- Testing and packaging completeness: Automated tests arrange state, exercise one behavior, and assert observable outcomes; pytest fixtures model reusable setup as a dependency graph. A strong answer also explains that fixture scope controls lifetime and caching. Parametrization creates independent cases. Mocks replace the name used by the code under test, not necessarily the original definition. The main warning is: Coverage measures execution, not correctness; patching the wrong import path produces deceptive tests.
CAPSTONE: Personal Finance Tracker CLI
- Architecture & models: A data class generates repetitive value-object methods from annotated fields. A strong answer also explains that the decorator rewrites the class by adding methods such as
__init__, comparison, and representation according to options.frozenblocks normal assignment but is not deep immutability. The main warning is: Usedefault_factoryfor mutable defaults and validate nested mutable state. - Advanced patterns: A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. A strong answer also explains that decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references.
wrapspreserves metadata and the wrapped chain. The main warning is: Keep retries bounded and restricted to transient, idempotent operations. - Testing: Automated tests arrange state, exercise one behavior, and assert observable outcomes; pytest fixtures model reusable setup as a dependency graph. A strong answer also explains that fixture scope controls lifetime and caching. Parametrization creates independent cases. Mocks replace the name used by the code under test, not necessarily the original definition. The main warning is: Coverage measures execution, not correctness; patching the wrong import path produces deceptive tests.
Professional standard
A complete response identifies the boundary, guarantee, state owner, lifecycle, failure, and proof. Award less credit to answers that name tools without explaining why their guarantees fit the requirement.
Mastery check
How well can you recall this?
Finished this lesson?