- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Python Type Hints
Python Type Hints
Type Hints and Clean Code in Python
IntermediateLesson 8 of 9 in Intermediate Python Course
What you will learn
- Add type hints to variables, parameters and return values, describe collections and missing values precisely, and pick the special types that say exactly what a value may be.
- Write basic annotations and know what they doRead and write annotations for parameters, return values and variables, and understand that Python records them but does not enforce them.
- Annotate collections, unions and missing valuesDescribe lists, dictionaries, sets and tuples by their contents, combine types with unions, and handle values that may be None safely.
- Describe values precisely with special typesChoose between Any and object, and use Callable, Literal, Final, TypedDict, NewType and type aliases to state exactly which values are allowed.
- Write basic annotations and know what they do
- Run a type checker such as mypy, read and fix its reports, and configure how strictly it checks a growing codebase.
- Run mypy and read its reportsRun a type checker on files or a package, interpret each part of an error message, and use inference, reveal_type and narrowing to fix the cause.
- Configure strictness and adopt typing graduallySet up mypy in pyproject.toml, raise strictness step by step, handle untyped libraries and silence errors only in a targeted way.
- Run mypy and read its reports
- Use type parameters to write functions and classes that work for many types without losing precision, and use protocols and class-level hints to type object-oriented code.
- Write generic functions with type parametersLink the types of a function's inputs and outputs with type parameters, and limit them with bounds and constraints.
- Build generic classes and choose flexible parameter typesWrite generic container classes, define generic aliases, and use variance to decide which collection types to accept and return.
- Type classes, methods and protocolsAnnotate attributes and methods, use Self and override, and describe required behavior with protocols instead of base classes.
- Write generic functions with type parameters
- Apply the PEP 8 conventions for layout and naming, automate them with formatters and linters, and document code with clear docstrings and comments.
- Apply PEP 8 layout and namingLay out and name code the way PEP 8 recommends, and know the reasoning and the limits of the guide.
- Automate style with linters and formattersUse a formatter to lay out code automatically and a linter to find errors and style problems, configure both in the project and run them on every change.
- Document code with docstrings and commentsWrite PEP 257 docstrings in a consistent style for modules, classes and functions, and write comments that explain why rather than what.
- Apply PEP 8 layout and naming
- Spot the signs of hard-to-maintain code, and improve it in small, behavior-preserving steps backed by tests and tools.
- Recognize common code smellsName the typical warning signs in functions and modules, and judge when a smell is worth fixing.
- Refactor safely in small stepsChange the structure of code without changing its behavior, using tests, tools and version control as a safety net.
- Apply core refactorings to small functionsImprove functions with extract function, rename, named constants, guard clauses, removal of duplication, parameter objects and clearer arguments, checking each step.
- Recognize common code smells
Python Type Hints study guide
1Describe the values your code expects
A function signature can tell a reader what to pass in and what comes back. Type hints make that information available to editors and checkers as well. Start with simple values, then describe the contents of collections and the possibility of missing data. More precise types let you distinguish a fixed choice, a record and an identifier, while keeping clear which guarantees come from a checker and which require running code.
1.1 Annotations describe expected types
A type hint names the type a value is expected to have. It makes an interface readable without tracing every line of the function. PEP 484 established their standard meaning; PEP 526 added variable annotations.
Read a function signature
def greet(name: str, times: int = 1) -> str:
return ("Hello, " + name + "! ") * times
message = greet("Ada", 2)
The colon after name says it expects a string. times expects an integer and has a default of 1. The arrow describes the return value: a string. The call produces "Hello, Ada! Hello, Ada! ". The default makes the second argument omissible; the hint describes its type.
Hints use types, not example values. Write factor: float, not factor: 2, and -> list[int], not -> []. The built-in names int, float, str, bool and bytes work directly. Use -> None for a function that finishes without a useful result, such as one that prints a message. Do not assign that call to a result variable as though it returned computed data.
Know what happens when code runs
Python does not enforce these hints. greet(42) enters the function; the string addition then raises TypeError. An annotation also does no conversion:
age: int = input("Age? ") # A checker reports a mismatch.
age = int(input("Age? ")) # This explicitly converts the input.
The first line still stores a string at runtime. Editors use annotations for completion and navigation, static checkers use them to find incompatible operations, and some libraries deliberately inspect them. Dataclasses use annotations to identify fields. These uses do not turn hints into general runtime validation.
For numeric arguments, a checker accepts an int where float is expected, and either where complex is expected. A function taking float can therefore accept 3 without spelling its parameter as int | float. That acceptance does not convert the integer object before the call.
Add hints where they clarify the contract
Checkers infer many local types. After total = 0, the inferred type is int. An empty collection often needs more help: names: list[str] = [] records what will be stored there. Annotate public function boundaries first, then work inward. Gradual typing lets annotated and unannotated code coexist; an unannotated parameter generally behaves as Any, allowing unchecked operations.
Use no space before the annotation colon, one after it, and spaces around the return arrow. An annotated default uses spaces around = (times: int = 1); an unannotated default does not (times=1).
Refer to a class before it is fully defined
On Python 3.12 and 3.13, a method annotation using its enclosing class name needs a forward reference:
class Point:
def copy(self) -> "Point":
return Point()
At that moment the class name has not yet been bound. Quoting it avoids an immediate lookup. Alternatively, put from __future__ import annotations at the start of the module. Python 3.14 and later defer annotation evaluation, so the unquoted name also works once the class has been defined.
Key Takeaways
- Annotations state expected types; conversion and runtime validation require code.
- Annotate parameters and returns, and add variable hints where inference needs help.
- Use
-> Nonefor functions without a useful return value. - Python accepts integers for a
floatparameter under static typing rules. - Quoted forward references work on Python 3.12 and later.
1.2 Collection contents and missing values
The outer container type tells only part of the story. A checker also needs to know what may be inside it and whether a value may be missing.
Describe each layer
Use list[str] for a list of strings, set[int] for a set of integers and dict[str, float] for string keys mapped to float values. A list has one element-type argument. list[int, str] is invalid; list[int | str] describes a list whose individual elements may be integers or strings.
Nested hints follow the data's shape:
scores: dict[str, list[int]] = {
"Ada": [90, 85],
"Lin": [77],
}
Read from the outside inward: a dictionary, string keys, list values, integer elements. Older code uses List, Dict and Set from typing. These are older aliases; modern code uses the built-ins. Ruff's UP006 rule can modernize the older form.
A tuple can describe positions separately. tuple[str, int, bool] means exactly three items in that order. tuple[int, int] accepts (3, 4) but rejects (3, 4, 5). To allow any number of integers, use tuple[int, ...]; the ellipsis changes the length rule.
A union describes alternatives
int | str means one value may be either type. It does not mean the value supports every operation available on both types. Before adding to it as an integer or calling a string method, establish which case you have. Older code writes Union[int, str].
str | None includes missing data. The older spelling Optional[str] means exactly the same thing. The word "optional" says nothing about whether a caller may omit an argument. A parameter can be left out only when it has a default:
def label(name: str | None) -> str:
if name is None:
return "Guest"
return name.upper()
label(None) is valid; label() is missing a required argument. Adding = None to the parameter would allow that second call too.
Narrow the type before using it
def find_user(users: dict[int, str], user_id: int) -> str | None:
return users.get(user_id)
name = find_user({1: "Ada"}, 1)
if name is not None:
print(name.upper())
dict.get may return None when the key is absent. The checker follows the test and treats name as str inside the block. This is type narrowing. A truth test such as if name: also excludes an empty string; is not None keeps that valid string case.
An early return or raise removes a case from the remaining path. In label, the missing-name branch returns, leaving only strings below it. isinstance narrows other unions: after if isinstance(value, int): return str(value + 1), a remaining int | str value is a string.
If a default is None, include it in the annotation: width: int | None = None. Writing width: int = None gives a default that conflicts with the declared type. Read the hints of lookup functions such as dict.get, re.match and os.environ.get; their missing-result cases need handling before their results are used.
Key Takeaways
- Collection type arguments describe contents, including nested shapes.
- A fixed tuple lists positions;
tuple[T, ...]permits variable length. Optional[T]meansT | None; a default controls argument omission.- Use
is None,isinstanceor early exits to narrow a union safely.
1.3 Choose a type that expresses the rule
Broad hints are quick to write, but they can leave important rules unstated. Choose a type that describes the operations, fields or choices the function actually needs.
Any and object allow different operations
| Hint | Values accepted | Operations the checker allows |
|---|---|---|
Any | Any value | Any operation, without checking it |
object | Any value | Only operations supported by all objects |
With value: Any, value.fly() passes a type check whether or not that method exists. With value: object, the same call is rejected. Narrow an object with isinstance before using a type-specific method. Results obtained through Any often stay Any, so one unchecked boundary can hide errors farther along a program.
State function shapes and fixed choices
from collections.abc import Callable
from typing import Final, Literal
type Mode = Literal["r", "w"]
MAX_RETRIES: Final = 3
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)
Callable[[int], int] describes one integer argument and an integer result. apply(lambda n: n * 2, 5) returns 10. Passing len fails a type check: an integer does not meet its input requirement.
Literal["r", "w"] permits those exact values, so a typed parameter using Mode rejects "x". It suits a small fixed set; an Enum can give richer named choices. Final tells the checker that a name must not be reassigned. It does not freeze an object: a dictionary stored in a final name can still have its contents changed.
Describe a fixed dictionary record
from typing import NotRequired, TypedDict
class Movie(TypedDict):
title: str
year: int
subtitle: NotRequired[str]
movie: Movie = {"title": "Up", "year": 2009}
Each key has a separate type. subtitle may be absent; its value, when present, is still a string. "year": "2009" is a type error. At runtime the value is an ordinary dictionary, and a TypedDict annotation does not inspect incoming JSON. Validate external data before trusting that shape. For records created within your own code, a dataclass often provides a clearer object interface.
Separate a convenient name from a distinct identity
from typing import NewType
type Vector = list[float]
UserId = NewType("UserId", int)
def get_name(uid: UserId) -> str:
return f"user-{uid}"
Vector is a type alias: another name for the same type. A list[float] works wherever Vector is expected. Before Python 3.12, aliases commonly used Vector = list[float] or Vector: TypeAlias = list[float] with TypeAlias imported.
NewType makes a distinct static type. get_name(42) is rejected, while get_name(UserId(42)) is accepted. The runtime value is still the integer 42; the wrapper neither validates its range nor creates a separate integer subclass. Use it to keep identifiers apart, and use ordinary checks for rules such as a positive ID.
Key Takeaways
- Use
objectfor arbitrary values that must still be checked before specialized operations. Anyallows unchecked operations and can spread through expressions.Callabledescribes an input and output signature;Literalrestricts exact values.Finalprevents static reassignment of a name, not mutation of its contents.TypedDictassigns types to fixed keys;NotRequiredallows a key to be absent.- A type alias renames a type;
NewTypecreates a distinct static identity.
2Find and fix type errors
A type checker compares your code with its declared and inferred types before the program runs. Its reports become useful when you can connect a line and error code to the value that caused the mismatch. Learn to inspect inferred types, fix control-flow gaps and bring an existing project under checking in manageable steps. Shared settings and pinned tool versions make the results repeatable in the editor and in automated checks.
2.1 Follow a type checker report to its cause
A static type checker reads source code without executing the program. It checks whether operations and calls fit the types it knows. mypy is a common choice; pyright is another and supplies Pylance's type analysis. ty and Pyrefly are newer alternatives. A project should choose and pin a checker so the editor and automated checks agree.
Run mypy and read the location
Install it in your environment with python -m pip install mypy. Run mypy app.py for one file or mypy src/ for a directory. A report looks like this:
basics.py:6: error: Argument 1 to "greet" has incompatible type "int"; expected "str" [arg-type]
Start at line 6 of the named file. The first argument has an integer type; the function requires a string. The final code, arg-type, identifies the check involved. Fix the caller if it passed the wrong value. Change the signature only if the function truly supports the broader input.
| Error code | What to inspect |
|---|---|
assignment | A value conflicts with the receiving variable's type. |
return-value | A returned expression conflicts with the return annotation. |
union-attr | One possible union member lacks the attribute. |
attr-defined | The known type lacks the attribute. |
call-arg | An argument name or argument count does not match. |
return | A result-producing path has no return statement. |
Inspect the paths through a function
def total(values: list[int]) -> int:
if values:
return sum(values)
return 0
Without the last line, an empty list would fall off the end and return None. The -> int contract requires an integer on that path too. Follow every branch, including empty and missing cases, before weakening a return annotation.
For an optional value, a report about a missing attribute often points to an unhandled None case. An early exit such as if name is None: return "guest" leaves only strings afterward. Adding an ignore would hide the path; adding the check makes the operation safe.
Ask what type mypy inferred
from typing import reveal_type
nums = [3, 4, 5]
reveal_type(nums)
mypy reports a note identifying list[int]. This is useful when a mismatch seems surprising: inspect the value near its source and again after a branch. The import also lets the diagnostic run in Python 3.11 and later; without it, executing the name would raise NameError. Remove the diagnostic when finished.
Know which code is being checked
By default, mypy skips a function body with no annotations. def broken(): return "a" + 1 can therefore pass a default check. --check-untyped-defs inspects such a body and finds this incompatible addition, but its unannotated parameters remain Any. Annotating the boundaries gives the checker more information than that flag alone.
A successful run means no issues were found under the selected settings. Tests are still needed for wrong formulas, side effects and unexpected external values. A declared JSON shape is not evidence that the data received at runtime matches it.
Key Takeaways
- Read the location, expected type, actual type and error code together.
- Inspect every return path, including empty and missing cases.
- Use
reveal_typeto inspect inference, then remove the diagnostic. --check-untyped-defschecks bodies but leaves unannotated parameters asAny.- Type checks and runtime tests catch different kinds of mistakes.
2.2 Make checking repeatable and tighten it gradually
A checker is most useful when everyone runs it against the same files with the same rules. Store those choices in the project, then raise strictness where the code is ready for it.
Put the settings in pyproject.toml
[tool.mypy]
python_version = "3.12"
files = ["src"]
warn_unused_ignores = true
[[tool.mypy.overrides]]
module = "myapp.core.*"
disallow_untyped_defs = true
The override requires complete function annotations in the selected package while the rest of the project can remain less strict. Annotate new code and frequently used public functions first. strict = true, or mypy --strict, enables a collection of checks including missing annotations, generic types without type arguments, unchecked returns of Any and unused ignores. The exact collection changes between releases, so pin the version and review upgrades.
Repair a mismatch before suppressing it
Use narrowing for a value whose type can be checked. isinstance(value, str) both tests the running value and lets the checker treat it as a string in that branch.
cast(str, value), imported from typing, makes a claim to the checker. It returns the same value without inspecting or converting it. A cast is appropriate only when you already have sound evidence the checker cannot express. It cannot make an integer support string methods.
For a genuine limitation that cannot yet be resolved, target the suppression:
result = legacy_call(value) # type: ignore[arg-type]
This ignores one error code on one line. A bare ignore can hide unrelated future errors. warn_unused_ignores finds suppressions that can be removed after the code or its library hints improve.
Give the checker information about libraries
A typed library can ship annotations with a py.typed marker. Another option is a separate stub package, containing .pyi files with signatures and placeholder bodies. Many community stubs come from typeshed. Install the stub package that corresponds to the library, such as types-requests or types-PyYAML.
An import-untyped report means typing information is missing; import-not-found means the checker could not find an implementation or stub. Check the active environment and installed dependencies before hiding either report. If no typing information is available, apply ignore_missing_imports = true only to the affected module in an override. Values imported through that gap behave as Any.
Keep annotation-only imports out of runtime paths
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from myapp.models import User
def user_label(user: "User") -> str:
return user.name
The checker sees the import; Python skips it at runtime. The quoted annotation works on Python 3.12 and later. With deferred annotations you can also use the unquoted name, but code that runs still cannot construct User from this skipped import. This pattern can break a circular import when the dependency is needed only to describe a type.
Run the pinned checker in the editor, before commits and on automated change checks. The same project settings should apply in each place.
Key Takeaways
- Store shared settings in
pyproject.tomland pin the checker version. - Use module overrides to adopt stricter checks a piece at a time.
- A cast asserts a type without checking or converting the value.
- Use code-specific ignores and remove them when they become unnecessary.
- Stubs and
py.typedprovide library typing information; missing-import ignores introduceAny. TYPE_CHECKINGimports are available to static analysis, not ordinary runtime code.
3Keep reusable code precisely typed
Reusable code should work across types without forgetting what those types are. A type parameter carries an input's type through to its result, while collection interfaces describe the operations a function needs. Classes add a further choice: require membership in a class hierarchy, or describe the behavior an object must provide. These tools let you accept a useful range of inputs while preserving the information callers need afterward.
3.1 Type parameters connect inputs to results
A reusable function often has a relationship between its inputs and output. If it returns an item from a sequence, the result should have that sequence's element type. A type parameter gives that relationship a name.
Keep the element type
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
number = first([3, 1, 2])
letter = first("abc")
This Python 3.12 syntax declares T after the function name. The checker chooses it at each call: number is an int, and letter is a str. The function needs a nonempty sequence to return successfully; a hint about its element type does not guarantee its length.
Using Sequence[Any] -> Any loses that connection. Using Sequence[int | str] -> int | str also loses precision for a caller that supplied only integers. A type parameter preserves a relationship; a union describes allowed alternatives.
Older code declares the variable separately:
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]
The two versions express the same typing relationship. Short names such as T, K and V are common; a descriptive CapWords name can be clearer when several roles appear. Multiple parameters can link separate roles, such as a dictionary's key and value types.
Bound a type parameter by required behavior
from collections.abc import Sized
def longest[T: Sized](a: T, b: T) -> T:
if len(a) >= len(b):
return a
return b
The upper bound Sized requires support for len. It gives the body permission to call len(a) and len(b) while preserving the chosen argument type in the result. longest([1, 2], [3]) returns [1, 2], typed as list[int]. Integers are rejected because they lack a length. The older declaration is T = TypeVar("T", bound=Sized).
A bound permits its type and subtypes; it is not a list of unrelated choices. If all a function does is return len(value), its signature can simply take Sized and return int. A parameter appearing only in that one input position adds no useful link.
Constrain a type to a fixed set
def concat[S: (str, bytes)](a: S, b: S) -> S:
return a + b
Each call chooses str or bytes for S. Two strings work, as do two byte strings. Mixing "ab" and b"cd" fails because no single permitted choice fits both arguments. Independent str | bytes annotations would allow mixed inputs into the signature and would not make their addition safe.
The older form is S = TypeVar("S", str, bytes). A bound uses one type after the colon; constraints use a parenthesized list of at least two types. Choose the form by the relationship you need to preserve, then check both a valid call and a call that should be rejected.
Key Takeaways
- A type parameter preserves a relationship between type positions.
- Python 3.12 declares function parameters after the name; older code uses
TypeVar. - An upper bound supplies operations shared by permitted types and their subtypes.
- Constraints make one call choose from a fixed list of types.
- A union of inputs does not preserve the same input-to-output relationship.
3.2 Generic containers and flexible inputs
A generic class gives each instance a consistent type contract. Parameter annotations can then choose whether they need a particular mutable container or only a smaller set of reading operations.
Type an instance's stored values
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
stack = Stack[int]()
stack.push(5)
number = stack.pop()
T connects storage, insertion and removal. This instance accepts integers and returns integers. stack.push("five") is a static error. The runtime class still uses an ordinary list, and popping an empty stack still raises IndexError.
Older code imports TypeVar and Generic, declares T = TypeVar("T"), and writes class Stack(Generic[T]):. Generic aliases are shorter ways to reuse a shape: type Pair[T] = tuple[T, T] makes Pair[float] mean tuple[float, float].
Why lists are invariant
A string is an object, but a list[str] cannot safely stand in for a list[object]:
def add_item(items: list[object]) -> None:
items.append(1)
names: list[str] = ["Ada"]
# add_item(names) is rejected by the checker.
If the call were allowed, names would contain an integer despite its list[str] contract. Invariance blocks that substitution. The same issue means a variable typed list[int] cannot be supplied to a list[float] parameter, despite the numeric compatibility of individual integers and floats.
Request only the operations you need
| Parameter type | Needed operations |
|---|---|
Iterable[T] | Loop over values. |
Sequence[T] | Read indexed items and length. |
Mapping[K, V] | Read keys and values. |
list[T], dict[K, V] | Change the concrete container. |
Import the abstract interfaces from collections.abc. A function that only reads can accept Sequence[object] and receive a list[str] safely. The interface offers no insertion operation. Sequence and Iterable are covariant in their element types: this substitution follows the element-type relationship. Sequence[float] can also accept a list[int].
For Mapping[K, V], only the value parameter is covariant. A dict[str, int] fits Mapping[str, object], but not Mapping[object, int]: the key parameter stays invariant. Return a precise concrete type when you create one, such as list[str], so callers retain useful operations.
Check callable inputs in the other direction
A callback accepting object and returning int fits Callable[[int], int]. It can handle every integer the caller may supply. A callback requiring a narrower input cannot promise that. The return also has to fit: accepting object but returning str fails the integer-result contract. Check the input promise and the output promise separately.
Key Takeaways
- A generic class connects the types stored, accepted and returned by an instance.
- Mutable lists are invariant because writes could violate a narrower element type.
- Choose
Iterable,SequenceorMappingfor the reading operations a function needs. Mappingis covariant in values and invariant in keys.- A compatible callback must accept the promised inputs and return a compatible result.
- Generic aliases name reusable parameterized shapes.
3.3 Class attributes, method results and protocols
Class hints describe both stored data and the promises methods make to callers. A protocol describes a required shape, allowing unrelated classes to satisfy the same contract.
Annotate the right kind of attribute
In a typed __init__, self.side = side inherits the type of side. Annotate the constructor -> None; leave self unannotated. Class-body declarations such as name: str describe instance fields and are how dataclasses declare their data. A ClassVar[int] marks a shared class attribute and is excluded from dataclass fields.
Use Self for a method returning its own instance:
from typing import Self
class Counter:
def __init__(self) -> None:
self.value = 0
def increment(self) -> Self:
self.value += 1
return self
class LoudCounter(Counter):
pass
LoudCounter().increment() retains type LoudCounter. Annotating the return as Counter would lose that subclass information. Self is available from typing in Python 3.11 and later.
Keep overrides compatible
Import override from typing on Python 3.12 and later and place @override above an intended replacement method. The checker reports a typo if no base method has that name. The decorator does not enforce the signature at runtime.
An override must accept the calls allowed by the base method and return a compatible result. If the base accepts describe(verbose: bool), a replacement that requires an extra extra: str breaks existing calls. Type checking catches that incompatibility even when the method name is correct.
Describe behavior without requiring inheritance
from collections.abc import Iterable
from typing import Protocol
class HasArea(Protocol):
def area(self) -> float:
...
class Square:
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side ** 2
def total_area(shapes: Iterable[HasArea]) -> float:
return sum(shape.area() for shape in shapes)
Square never inherits from HasArea, yet its compatible area method satisfies the protocol. Two squares with sides 2.0 and 3.0 produce 13.0. A class without area, or with area() -> str, fails the static contract.
This is structural typing: membership follows the available typed members. Ordinary classes use nominal typing, where the declared class hierarchy establishes the relationship. Iterable, Iterator, Sized and Hashable receive structural treatment from checkers. A valid __iter__ must return an iterator, not an integer. Sequence and Mapping require nominal membership; merely defining __len__ and __getitem__ does not establish Sequence[int].
@runtime_checkable permits an isinstance check against a protocol, but it checks member presence, not signatures or return types. An object with an area attribute can pass that runtime check while failing the static HasArea contract.
Key Takeaways
- Annotate constructor inputs and
-> None;ClassVarmarks shared class data. Selfpreserves the receiver type, including subclasses, in fluent method results.@overridehelps detect unintended method names; compatible signatures still matter.- A protocol is satisfied by compatible members without required inheritance.
- Runtime protocol checks examine member presence, not full type signatures.
4Make code consistent and useful to readers
Readable code combines predictable layout, clear names and useful explanations of its interface. PEP 8 supplies conventions; a formatter applies layout choices; a linter points out likely bugs and style problems. Documentation adds meaning that types alone cannot express, such as units, limits and side effects. Choose consistent project settings so these jobs support each other and the reader can concentrate on what the program does.
4.1 PEP 8 layout and naming
PEP 8 is Python's style guide, originally written for the standard library. Its conventions help readers recognize code quickly. Project consistency takes priority, and style changes should preserve existing compatibility.
Make the layout predictable
Indent each level with four spaces. Do not mix tabs and spaces. PEP 8 recommends a 79-character code line and 72-character comments and docstrings; teams may agree on up to 99 for code. Black and Ruff default to 88. Follow the chosen project setting and wrap within parentheses, square brackets or braces:
result = calculate_total(
prices,
discount=0.1,
)
The enclosing parentheses allow the expression to continue without a backslash. Use two blank lines around top-level functions and classes and one between class methods. Separate logical groups within a function when that helps the reader see its steps.
Place imports at the top. Group standard-library modules, third-party packages and local modules in that order, with a blank line between groups. Use separate lines for import os and import sys; a from import may name several members. Avoid wildcard imports because the origin of names becomes hard to track.
Choose names that show their role
| Role | Convention | Example |
|---|---|---|
| Function, method, variable | snake_case | load_scores |
| Class | CapWords | ScoreReport |
| Module constant | UPPER_CASE | MAX_RETRIES |
| Internal name | Leading underscore | _parse_line |
| Exception class | Ends in Error | InvalidScoreError |
Module names are short and lowercase, with underscores when helpful. Avoid the single-character names l, O and I; fonts can make them look like digits. A useful name describes meaning, not just a type: total_price tells more than number.
Put spaces where they clarify structure
Write total = price + tax, items[0] and round(value, ndigits=2). Put a space after a comma, none just inside parentheses and none before a comma. Keyword arguments and unannotated defaults have no spaces around =. An annotated default does: discount: float | None = None. Remove trailing whitespace.
Prefer direct Python expressions
Use value is None and value is not None for the singleton. Use isinstance(value, int) to allow the type and its subclasses. An empty sequence is false, so if not items: expresses the emptiness check directly. Use the Boolean value itself instead of comparing it with == True. String prefix and suffix checks read clearly as text.startswith("id-") and text.endswith(".csv").
Catch the specific error you can handle. A bare except: also catches KeyboardInterrupt and SystemExit, so it can swallow a user's attempt to stop the program. except Exception: catches ordinary exceptions but still deserves a clear recovery plan. A named def also makes a traceback clearer than assigning a lambda to a name.
A cleanup such as renaming Total to total may affect callers. Keep broad formatting changes separate from a bug fix so each change is easy to inspect, and follow the surrounding style when editing an existing module.
Key Takeaways
- Use four spaces per indentation level and the project’s line-length setting.
- Group imports by origin and give names conventional, meaningful forms.
- Use identity checks for
Noneand specific exception handlers. - Keep large style cleanups separate from behavior changes.
4.2 Format layout and lint for problems
Formatting and linting both automate code quality work, but they answer different questions. A formatter chooses the layout. A linter looks for problems in the code it reads.
Give each tool its job
Black applies a consistent format with few configuration choices. Ruff also has a formatter, designed for close compatibility with Black. Choose one formatting tool for a project. Its work includes spaces, quotes, line breaks and trailing commas; it does not decide what an exception handler should catch.
Ruff's linter combines rule families from several tools. Flake8 combines style, Pyflakes findings and a complexity check. Pylint offers broader checks, including limits on parameter counts. These tools analyze source without running the program.
| Ruff family | Purpose | Example finding |
|---|---|---|
E, W | Style conventions | E711: == None |
F | Likely code errors | F401: unused import |
I | Import ordering | I001: unsorted imports |
B | Bug-prone patterns | B006: mutable default |
N | Naming | N802: function name |
UP | Modern syntax | UP006: old collection alias |
D | Docstrings | Convention-dependent documentation checks |
C90 | Complexity | C901: too many paths |
ANN | Annotations | Missing type information |
Read a finding before applying a fix
def add(item: int, items: list[int] = []) -> list[int]:
items.append(item)
return items
The default list is created once when def executes. add(1) returns [1]; a later add(2) returns [1, 2]. A formatter may leave that logic untouched. B006 identifies the risk, and the repair creates a fresh list only when no list was supplied:
def add(item: int, items: list[int] | None = None) -> list[int]:
if items is None:
items = []
items.append(item)
return items
Using if not items: would also replace a caller's empty list, changing whether that original object is mutated. The identity check handles exactly the omitted-list case.
ruff check --fix applies available safe fixes for enabled rules, such as unused-import removal and import ordering. Some fixes need --unsafe-fixes, and many findings need a human choice. Review the diff and run checks after a fix; renaming public functions and choosing exception types require understanding callers.
Share the configuration and run it automatically
[tool.ruff]
line-length = 88
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
Explicit selection makes the intended rule families visible even as defaults change. Add ignore only for rules the project has deliberately excluded. A targeted # noqa: F401 applies to one code on one line; a blanket # noqa hides more.
Use ruff format . locally to rewrite layout. Automated checks can use ruff format --check ., or black --check . when Black is the formatter, and ruff check . to lint. Editor integration and pre-commit hooks catch findings early; continuous integration checks each proposed change.
Key Takeaways
- A formatter rewrites layout; a linter reports likely bugs and style problems.
- Ruff rule prefixes identify the rule family; select families explicitly.
- Mutable defaults persist across calls; use
Noneand create a new collection in the body. - Review automatic fixes and use targeted suppressions.
- Automated checks should verify both formatting and lint results.
4.3 Docstrings explain the interface
Types tell a caller what kind of value to pass. Documentation explains its meaning: which units apply, what restrictions hold and what the call changes.
Put a docstring first
A docstring is the first string literal in a module, class, function or method. Python exposes it through __doc__; help(), editors and documentation tools can display it. A # comment is not stored that way. A string placed after an assignment is not the function's docstring.
PEP 257 recommends triple double quotes. A one-line docstring states the action as a command and ends with a period:
from collections.abc import Sequence
def mean(values: Sequence[float]) -> float:
"""Return the mean of a nonempty sequence."""
return sum(values) / len(values)
The sentence adds the nonempty requirement. Repeating mean(values) -> float would add nothing that the signature does not already show.
Add details the caller needs
A multi-line docstring starts with a summary, then a blank line and the details. Put closing quotes on their own line. Document meaningful arguments, returned results, raised exceptions, side effects and restrictions.
from typing import Literal
type Zone = Literal["domestic", "international"]
def shipping_cost(
weight_kg: float, zone: Zone, *, express: bool = False
) -> float:
"""Return the shipping cost of one parcel.
Args:
weight_kg: Parcel weight in kilograms; must be positive.
zone: "domestic" or "international".
express: Double the weight charge for faster delivery.
Raises:
ValueError: If weight_kg is zero or negative.
"""
if not weight_kg > 0:
raise ValueError("weight must be positive")
base_fee, rate = (5.0, 1.5) if zone == "domestic" else (12.0, 3.0)
weight_charge = weight_kg * rate
if express:
weight_charge *= 2
return base_fee + weight_charge
This Google-style docstring explains kilograms and what the flag doubles. Other established layouts are NumPy style, with underlined section headings, and reStructuredText style, with fields such as :param weight_kg: and :returns:. Pick one project convention. Ruff's D rules can check it when configured for that style.
Usage examples may use interactive prompts: >>> shipping_cost(2, "domestic") followed by 8.0. The standard doctest module can execute such examples to help keep them accurate. Document public modules, classes and functions; a clearly named private helper may need less explanation.
Write comments that supply a reason
count += 1 # Increment count. repeats the operation. # The API numbers pages from 1, not 0. explains a choice the code cannot explain by itself. Use complete sentences, one space after # and at least two before an inline comment.
When a comment exists only to decode a vague name, improve the name. When it describes a long block's purpose, consider extracting a named function. Update comments alongside code and delete commented-out code; version control retains the old implementation.
Key Takeaways
- A docstring is the first string literal and becomes
__doc__. - Use a command-style summary, then a blank line before multi-line details.
- Document meaning, units, limits, effects and exceptions that callers need.
- Choose one established docstring style and keep examples executable.
- Comments explain reasons the code cannot show; update or remove stale comments.
5Improve small functions without surprises
Hard-to-read functions often give warning signs before a bug appears: repeated formulas, unexplained values, deeply nested cases or arguments that are easy to mix up. Use those signs to choose a useful improvement. Tests record the current behavior, while type and lint checks help catch mistakes during the change. Work one step at a time, paying attention to return values, exceptions, mutations and the calls that already depend on the interface.
5.1 Recognize a smell and decide what it costs
A code smell is a warning sign that code may be difficult to understand or change. It invites investigation; it is not itself a confirmed bug. Look for the cost it creates for a reader or a future edit.
Follow a function with several smells
def shipping_cost(weight, express, zone):
if weight > 0:
if zone == "domestic":
if express:
return 5 + weight * 1.5 * 2
else:
return 5 + weight * 1.5
else:
if express:
return 12 + weight * 3.0 * 2
else:
return 12 + weight * 3.0
else:
raise ValueError("weight must be positive")
The formula is repeated four times, the nested branches hide the main calculation and the numbers lack names. A call such as shipping_cost(2, True, "domestic") also leaves the meaning of True unclear at the call site.
Name the warning signs
A long function does several jobs, such as reading data, computing a result and printing it. There is no universal line limit. A name requiring "and" or comments dividing several jobs can reveal a useful extraction point.
Deep nesting forces readers to remember several enclosing conditions. Guard clauses can handle invalid or special cases first, leaving the main case flatter. Duplicated code forces coordinated edits; when one copy is missed, the program can behave inconsistently.
Magic numbers and strings carry meaning that their spelling does not reveal. SECONDS_PER_DAY = 24 * 60 * 60 gives 86400 a name and an explanation. A long parameter list makes argument order hard to remember. Data clumps, such as street, city and postal_code traveling together, suggest a small parameter object. A flag argument selects behavior with a Boolean whose meaning may be hidden in a positional call.
Primitive obsession means using plain strings or numbers where meaningful distinctions or rules matter. Literal or an Enum can define a fixed choice of zones. NewType can keep a user ID distinct from an order ID. A dataclass can group related fields. These choices still need explicit runtime code for value rules such as positive weight: NewType("Zone", str) would allow wrapping the string "unknown".
Use measurements as clues
Ruff's C901 rule checks McCabe complexity, a measure of independent paths. Branches, loops and exception handlers add paths; the standard threshold is 10. Pylint's default maximum of five arguments is another review signal. A threshold crossing identifies code to inspect, not an automatic instruction to split it.
Also look for vague names, dead branches, unused imports and variables, commented-out code, shared mutable defaults and overly broad exception handlers. Linters find some of these; a reader must judge whether the function's jobs fit together.
Choose improvements where they help code that people regularly read or change. A one-use script may need no restructuring, while splitting a clear function into many vaguely named helpers can make it harder to follow.
Key Takeaways
- A smell points to a possible maintenance problem; inspect its actual cost.
- Duplication, deep nesting and unexplained literals make edits harder.
- Long parameter lists, data clumps and flags can make calls unclear.
- Precise static types express distinctions; runtime checks enforce value rules.
- Complexity and argument thresholds are review signals, not design verdicts.
- Improve names and structure where they make repeated reading or editing easier.
5.2 Record behavior before changing structure
Refactoring changes code structure while preserving observable behavior. That includes more than the usual returned number: callers can observe exceptions, printed output, mutations, side-effect order and the accepted interface.
Capture the current contract
Before changing the shipping calculation, record representative calls using the current parameter order:
| Existing call | Observed result |
|---|---|
shipping_cost(2, False, "domestic") | 8.0 |
shipping_cost(2, True, "domestic") | 11.0 |
shipping_cost(4, False, "international") | 24.0 |
shipping_cost(4, True, "international") | 36.0 |
shipping_cost(0.5, True, "domestic") | 6.5 |
shipping_cost(0, False, "domestic") | Raises ValueError |
These are characterization tests: they record what the implementation does now. Include boundaries and unusual inputs near the branches being changed. A test written only after rewriting the code can accidentally endorse the new behavior.
The express case doubles only the weight charge. For 2 kg domestically, the base fee is 5, the weight charge is 2 * 1.5 = 3, and express makes that charge 6. The total is 11, not 16. This is the sort of grouping error a type checker cannot detect.
Check the less obvious paths
The original code sends every zone other than "domestic" to the international branch. For 2 kg with express off, "Domestic" gives 18.0. A table indexed directly by the supplied string would instead raise KeyError. Add a Literal annotation to expose such calls statically, but remember that the annotation does not stop the old runtime fallback.
A guard clause also needs to preserve the original condition. if not weight > 0: raise ValueError(...) rejects everything that fails the positive comparison. This exactly mirrors the old outer if. Changing it to weight <= 0 treats a floating-point NaN differently because NaN satisfies neither comparison. Keep the original decision while restructuring; decide new validation rules separately.
Make one change and verify it
A safe sequence is: record the behavior, make one focused edit, run the tests, run the type checker and linter, and inspect the diff. If a check fails, repair or undo that small step before continuing. Version control gives a known working point to return to.
Editor rename and extract-function commands can update references mechanically. The type checker helps locate callers affected by changed types or signatures. Tests check behavior that static analysis cannot see, including mutation of a caller-owned list and the order of writes.
Move interfaces deliberately
Renaming a parameter can break keyword calls. Reordering parameters can leave positional calls running with the wrong meanings. Making a parameter keyword-only can reject calls that previously worked. Migrate these interfaces in a separate step: introduce the new form, move callers and their tests, then remove the old form.
A feature addition or a bug fix changes behavior on purpose. Keep that purpose visible in its own step so a failure can be traced to the change that caused it.
Key Takeaways
- Observable behavior includes the interface, errors, output, mutation and effect order.
- Characterization tests record existing calls and outcomes before restructuring.
- Keep fallback cases and exact branch decisions when making a behavior-preserving edit.
- Make one focused change and run tests, type checks and lint before continuing.
- Migrate interface changes and deliberate behavior changes as separate steps.
5.3 Apply a small refactoring and verify it
Choose a refactoring that removes a specific reading or editing difficulty. Keep each step small enough that a failed check has an obvious place to look.
Give a calculation its own name
If a report mixes averaging with presentation, extract the calculation:
from collections.abc import Sequence
def mean(values: Sequence[float]) -> float:
return sum(values) / len(values)
def print_report(scores: Sequence[float]) -> None:
print(f"Average: {mean(scores):.1f}")
For [72, 85, 90], the mean is 247 / 3, and the report prints "Average: 82.3". Preserve the empty-input behavior unless a separate change defines a new rule. Use editor rename for a vague name such as t, replacing it with a meaningful name such as total_price throughout its references.
Flatten the special case and share the formula
The shipping function can keep its existing argument order and fallback behavior while expressing its calculation once:
from typing import Final
DOMESTIC_BASE: Final = 5.0
INTERNATIONAL_BASE: Final = 12.0
DOMESTIC_RATE: Final = 1.5
INTERNATIONAL_RATE: Final = 3.0
EXPRESS_MULTIPLIER: Final = 2
def shipping_cost(weight: float, express: bool, zone: str) -> float:
if not weight > 0:
raise ValueError("weight must be positive")
if zone == "domestic":
base_fee, rate = DOMESTIC_BASE, DOMESTIC_RATE
else:
base_fee, rate = INTERNATIONAL_BASE, INTERNATIONAL_RATE
weight_charge = weight * rate
if express:
weight_charge *= EXPRESS_MULTIPLIER
return base_fee + weight_charge
The guard clause handles the invalid case first. Named constants explain the fees and rates; the common formula appears once. The calls with 2 kg still return 8.0 and 11.0, and the old unknown-zone fallback remains.
A later, deliberate change can define type Zone = Literal["domestic", "international"] and use lookup tables. It lets the checker reject unknown zone strings. Direct table access also replaces the runtime fallback with KeyError for an unknown key, so test and document that change separately.
Clarify calls and grouped data
A separate interface step can use def shipping_cost(weight_kg: float, zone: Zone, *, express: bool = False) -> float:. A call then reads shipping_cost(2, "domestic", express=True). This renames and reorders parameters and makes the flag keyword-only. Migrate every positional and keyword caller; the original three-positional-argument call will no longer work.
When an address travels through several functions, introduce a parameter object:
from dataclasses import dataclass
@dataclass(frozen=True)
class Address:
street: str
city: str
postal_code: str
Replace related parameters with address: Address in a separate migration step. For simple loops, a built-in can state intent directly: replace an accumulation loop with sum(scores), or build cleaned names with [name.strip() for name in names if name.strip()]. Preserve filtering and side effects when choosing the replacement, then run the behavior and static checks.
Key Takeaways
- Extract a coherent calculation when its name helps the caller read clearly.
- Rename with reference-aware tools and replace meaningful literals with named constants.
- Guard clauses flatten branches; shared formulas separate choices from calculation.
- Handle lookup-table fallback changes separately from a pure refactoring.
- Keyword-only arguments and parameter objects require caller migration.
- Use built-ins and comprehensions when their behavior matches the original loop.
- Check each step before starting the next one.
Python Type Hints examples
1Make a data path readable to a checker
16 steps
- 1IntroductionFollow a value from input to result
A type hint tells a reader what kind of value a function expects. The useful contract also covers collections, missing data and special choices.
Follow a greeting function and a user lookup, then choose types for a record and its identifier. At each stage, distinguish what the checker can establish from what the running program actually does.
- 2ExplanationRead the function boundary
def greet(name: str, times: int = 1) -> str: return ("Hello, " + name + "! ") * timesnameexpects a string;timesexpects an integer and defaults to1. The arrow describes a string result.greet("Ada", 2)returns"Hello, Ada! Hello, Ada! ".A function that only logs a message uses
-> None, because it has no useful returned result. - 3ExampleAn annotation does no conversion
age: int = input("Age? ")The checker reports a mismatch, but executing this line still stores the input string. To obtain an integer, write
age = int(input("Age? ")).The same separation applies to a function call:
greet(42)is not blocked by its hint. It enters the function and fails when the body tries to add that integer to a string. - 4ChallengeDecide what the hint changes
A function is declared
def half(value: float) -> float:. Can a checker accepthalf(9)? Does the hint itself turn the argument into a float before the body runs?---reveal---
Yes, the call is accepted: static numeric rules permit an integer where a float is expected. No conversion is performed by the annotation. Any conversion comes from executable operations in the body.
- 5ExplanationMatch the nested data shape
scores: dict[str, list[int]] = { "Ada": [90, 85], "Lin": [77], }Read each layer: string keys lead to lists of integer scores. A list takes one element type, so mixed elements use
list[int | str], notlist[int, str].A tuple can describe separate positions.
tuple[str, int]fixes the order and length;tuple[int, ...]allows any number of integers. - 6ExampleKeep the missing result in the contract
def find_user(users: dict[int, str], user_id: int) -> str | None: return users.get(user_id)A missing dictionary key returns
None, so the hint includes that alternative.Optional[str]is the older spelling ofstr | None.Neither form lets a caller omit
user_id. A default controls omission; a union controls the values an argument or result may hold. - 7ExampleNarrow before calling the method
name = find_user({1: "Ada"}, 1) if name is not None: print(name.upper())The checker knows that only strings reach
.upper()inside the block. This is narrowing. An early return forNonecan establish the same fact for the rest of a function.if name:would also exclude an empty string, which is a separate decision from checking whether data is missing. - 8ChallengeHandle a union on every path
A function receives
code: int | str. It should add two to an integer and return the result as text, or uppercase a string. Write the two branches.---reveal---
if isinstance(code, int): return str(code + 2) return code.upper()The first branch narrows to
intand returns. Only the string case reaches the final line. - 9Key InsightChoose how much checking to keep
Both
Anyandobjectcan receive arbitrary values. Their operations differ:Anypermits unchecked method calls, whileobjectrequires proof before a specialized method is used.For a function that accepts unknown data and inspects it,
objectkeeps the need for a check visible. UsingAnyto quiet an error can also hide later errors because expressions derived from it often stay unchecked. - 10ExampleDescribe a callback and its result
from collections.abc import Callable def apply(func: Callable[[int], int], value: int) -> int: return func(value)The callback must accept an integer and return an integer. Passing
lambda n: n * 2with5gives10.Passing
lenfails the contract: integers do not have the length operation its input requires. A callable hint describes both sides of the call. - 11ExplanationState choices and stable names
Literal["r", "w"]restricts a parameter to those exact values. A checker can reject"x"before the call runs. Use anEnumwhen a richer collection of named choices is helpful.MAX_RETRIES: Final = 3prevents reassignment in static checking.Finalprotects the name, not the contents of a mutable object, and Python itself does not enforce the declaration. - 12ExampleType each field of a dictionary
from typing import NotRequired, TypedDict class Movie(TypedDict): title: str year: int subtitle: NotRequired[str]A record needs a string title and integer year. The subtitle may be absent, but its value must be a string when present.
At runtime this is an ordinary dictionary. Annotating external JSON as
Moviedoes not inspect or repair the incoming values. - 13ConnectionSeparate an alias from an identity
type Vector = list[float]gives a type a convenient name. An ordinary float list can be used whereverVectoris expected.UserId = NewType("UserId", int)creates a distinct static identity. AUserIdparameter acceptsUserId(42)but rejects a plain42in static checking. The wrapper returns the same integer at runtime and adds no range or ownership validation. - 14ChallengeKeep a missing field distinct from None
A
TypedDictdeclarescomment: NotRequired[str]. A record omits the key; another contains"comment": None. Are both statically valid?---reveal---
Only the omitted key is valid.
NotRequiredpermits absence, whilestrstill controls the value when the key is present. To permit a presentNone, the field's value type would also need to includeNone. - 15ChallengeRepair a lookup result without hiding it
A checker rejects this final line. Repair it so a missing label returns
"unknown"and a present empty string stays an empty string.label = {3: "ready"}.get(item_id) return label.upper()---reveal---
if label is None: return "unknown" return label.upper()The branch handles missing data and narrows the remaining value. A cast would not protect the runtime call, and a truth test would also catch empty text.
- 16RecapRead the contract at each boundary
Before calling a function, read the parameter types and defaults separately. Before using its result, account for every declared alternative. For collections, follow the type arguments through each layer.
Use more precise types when the rule concerns exact choices, record fields or distinct identifiers. Keep conversion and validation in executable code: hints give tools information, while branches establish what is safe on the running path.
2Use checker reports to improve a project
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn a report into a useful edit
- 2ExplanationRun the checker in the active environment
- 3ExampleFind the source of an argument mismatch
- 4ExampleComplete the empty-input path
- 5TipInspect inference and checking coverage
- 6ChallengeFollow the branch behind a report
- 7ExplanationApply strictness where the code is ready
- 8Key InsightA cast is a claim to the checker
- 9ConnectionFind the missing library information
- 10TipImport types without importing runtime code
- 11ChallengeRepair a boundary and keep the check useful
- 12RecapCombine static evidence with behavior checks
3Preserve types as code becomes reusable
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionReuse an operation without losing its types
- 2ExplanationLink the input element to the result
- 3ExampleGive a generic body a needed operation
- 4ChallengeChoose one permitted type for a call
- 5ExampleConnect a stack’s storage and methods
- 6Key InsightA writable list cannot widen safely
- 7TipRequest the operations the body uses
- 8ChallengeMake a read-only helper flexible
- 9ConnectionA callback’s inputs and result both matter
- 10ExplanationDescribe instance data and shared data
- 11ExampleDeclare the behavior an area calculation needs
- 12ExampleUse the shared behavior
- 13ChallengeKeep inherited callers working
- 14Key InsightMember checks and ancestry checks differ
- 15ChallengeCombine a precise result with a behavior contract
- 16RecapKeep the promise callers depend on
4Set up code that is easy to read
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the next reading easier
- 2ExplanationMake structure visible
- 3ExampleShow a name’s role
- 4ChallengeKeep zero in a valid data path
- 5ExplanationSeparate layout from findings
- 6ExampleRead rule codes as clues
- 7ExampleCreate the omitted-argument list inside
- 8ChallengeChoose the check that finds the problem
- 9ExplanationMake documentation discoverable
- 10ExampleExplain the caller’s units and limits
- 11ChallengePut a reason in the comment
- 12ChallengeProtect behavior while improving the description
- 13RecapGive each quality tool a clear job
5Refactor a calculation in verified steps
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionImprove one difficulty at a time
- 2ExampleRead the repeated delivery cases
- 3ExplanationUse smells as investigation clues
- 4ChallengeChoose a useful improvement
- 5ExampleRecord the normal shipping cases
- 6Key InsightBehavior reaches beyond the usual result
- 7ChallengeFind the gap in a passing test
- 8ExampleMove the invalid case out first
- 9ExampleChoose rates before calculating
- 10ExampleApply express to the weight charge
- 11ChallengeCheck the shared formula in a new case
- 12ConnectionSeparate clearer choices from a new interface
- 13TipChoose names that remove explanation work
- 14ChallengePlan the next change after checks pass
- 15RecapKeep each verified change understandable
Python Type Hints practice questions
Set 1: Read types and follow simple contracts10 Practice Questions
Question 1 of 10
What does Python store after this assignment runs?
quantity: int = "17"
Show answerHide answer
"17"; annotations do not enforce a type at runtime. A checker reports that the value conflicts with int, but no conversion takes place. Calling int("17") would be the separate operation that creates an integer.Question 2 of 10
def badge(name: str | None) -> str:. A caller wants to omit the argument and receive the missing-name behavior. What signature change allows that?Show answerHide answer
str | None allows that default's type. Replacing the union with Optional[str] alone changes neither the allowed values nor whether the argument is required. The body must still handle the None case.Question 3 of 10
Show answerHide answer
object accepts arbitrary values while keeping type-specific operations checked. Narrowing with isinstance(value, str) then permits a string method. Any also accepts the inputs, but it lets the method call pass without establishing that the value is a string.Question 4 of 10
mypy reports Missing return statement [return] for this function. How can it meet its stated contract on every normal path?
def highest(values: list[int]) -> int:
if values:
return max(values)
The intended empty-list result is zero.
Show answerHide answer
None. A final return 0 supplies the specified integer result on that path while preserving max(values) for nonempty input. Returning None would still conflict with -> int.Question 5 of 10
Show answerHide answer
warn_unused_ignores reports suppression comments that are no longer needed. This helps remove stale exceptions as code or library hints improve. ignore_missing_imports instead suppresses missing typing information and can introduce unchecked Any values.Question 6 of 10
What result type does a checker infer for last((2.5, 7.5))?
from collections.abc import Sequence
def last[T](items: Sequence[T]) -> T:
return items[-1]
Show answerHide answer
T to float for this call. The return annotation is that same T, not the container type. Any would discard the relationship that the type parameter was introduced to preserve.Question 7 of 10
This function must accept both a list[int] variable and a tuple[float, ...] variable. It indexes values, and must keep a float result. What parameter annotation fits?
def midpoint(values: list[float]) -> float:
return (values[0] + values[-1]) / 2
Show answerHide answer
Sequence[float] permits indexing and accepts the integer list through covariance and numeric compatibility, as well as the float tuple. Iterable[float] permits looping but does not promise indexing. Sequence[object] would lose the arithmetic operations required in the body.Question 8 of 10
int | None, and zero is a valid count. What test enters the missing-value branch without treating zero as missing?Show answerHide answer
is None checks exactly the missing-value case and preserves zero as valid data. if not count would enter for both None and 0, changing the intended behavior. The identity test also gives the checker a clear narrowing condition.Question 9 of 10
duration_s: float and returns float. Its output is a speed in meters per second, and it raises ValueError for nonpositive duration. What documentation adds the most useful caller information?Show answerHide answer
float from the signature adds less value and still leaves the meaning of the returned number unclear.Question 10 of 10
street, city, postal_code, weight_kg. Every call passes the same three address values together, and several calls swap city and postal code. What focused change addresses the repeated error source?Show answerHide answer
Set 2: Handle missing data and improve code safely10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
What does this function return for the string ""?
def display(value: str | None) -> str:
if value is None:
return "missing"
return value.upper()
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
type ParcelId = int and ClientId = NewType("ClientId", int). A function takes client: ClientId. After parcel: ParcelId = 62, what happens to send(parcel) and send(ClientId(parcel)) in static checking and at runtime?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Why can default mypy checking miss the incompatible addition here, and what change checks this body without adding annotations?
def broken():
return "sample" + 3
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
def render(self) -> str: .... An unrelated class defines that exact compatible method without inheriting from the protocol. Can an instance be passed to a parameter typed with the protocol?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
ruff format has completed, but the source still contains except:. What next action addresses the remaining risk?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
elapsed_s / 86400 appears in several functions, all converting seconds to days. What focused change clarifies the repeated literal?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
base + mass_kg * rate * multiplier, where multiplier is 2 for express and 1 otherwise. A refactoring computes (base + mass_kg * rate) * multiplier. With base 7, mass 3 kg and rate 2, what reveals the error?Show answerHide answer
Save this lesson to see this answer.
Set 3: Trace contracts across functions and objects10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
("ready", 9)?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
TypedDict has name: str and note: NotRequired[str]. A value has been correctly validated against that shape. A function must return an uppercase note when present and "" when absent. What body handles both cases safely?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
value: int | str, the function returns from the isinstance(value, int) branch. What does a checker know about value on the next reachable line?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
types-... package. What should the project do before suppressing the import report?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Mapping[str, object]. Another expects Mapping[object, int]. With rows: dict[str, int], which calls are statically compatible?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
self is inherited by SpecialCounter. What return annotation preserves SpecialCounter in SpecialCounter().reset()?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
normalize(values: list[str]) -> None strips whitespace in the supplied list itself. What caller-relevant fact should its docstring make clear?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
if region == "local": ... else: .... A proposed rewrite indexes a two-key rate dictionary directly. Current tests cover only those two keys. What additional case exposes a possible behavior change?Show answerHide answer
Save this lesson to see this answer.
Set 4: Choose safe abstractions and small edits10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
class Link declares -> Link before the class name has been bound. What annotation spelling avoids that immediate lookup?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
value: int | str | None. It must return "absent" for None, the incremented integer as text for an integer, and uppercase text otherwise. What branch order gives a safe implementation?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
cast(str, raw), but raw still contains an integer from external input. The next line calls .strip(). What change can make the string path safe without pretending conversion occurred?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
len(a) and len(b) and returns one argument. What upper bound allows the length calls while keeping the selected argument's type?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
int and needs an int result. Available callbacks are read_object(value: object) -> int, read_text(value: str) -> int and describe(value: int) -> str. Which callback meets the full contract, and why?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
read() -> bytes. An unrelated object has read() -> str. Why can an instance check succeed while static assignment to the protocol is rejected?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
E, F and B. It wants import ordering checked automatically too. What configuration change addresses that need?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
quote(4, True, "near") and quote(weight=4, express=True, zone="near"). Its new signature is quote(weight_kg: float, zone: str, *, express: bool = False) -> float. What migration is necessary?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
score > 0; otherwise it raises ValueError. The refactor must preserve the branch even for a float NaN, for which both score > 0 and score <= 0 are false. What early-exit condition preserves it?Show answerHide answer
Save this lesson to see this answer.
Set 5: Diagnose changes across a typed codebase10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
RATES: Final = {"near": 1.2}. How does Final affect RATES = {} and RATES["near"] = 1.4 under static checking?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
[arg-type] and says an argument is str where int is expected. What should you inspect first?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
service.core.*, leave legacy modules under default rules and detect stale ignores everywhere. What configuration fits all three needs?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
def take(items: Sequence[int | str]) -> int | str: and then adds one to the result. Another caller supplies strings. What redesign preserves each caller's element type without promising a nonempty input?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
save(self, text: str, *, overwrite: bool = False) -> int. Its intended override is save(self, text: object, overwrite: bool, path: str = "data") -> int. What makes this replacement incompatible with the base contract?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Why is the string below not the function's docstring?
def label(code: int) -> str:
prefix = "item"
"""Return an item label."""
return f"{prefix}-{code}"
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
step1, step2 and so on. What is the strongest reason to reject the proposal as described?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
store(row) raises ValueError before changing storage. The old routine calls store(row), appends "saved" to the log and returns True. The rewrite appends "saved" first, then calls store(row) and returns True. What outcome distinguishes these executions?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
None on a missing key to raising KeyError, because every test uses a present key. The helper is still annotated -> str | None. What is the best next step before continuing the refactor?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
This helper must append to a caller-supplied empty list, but create a fresh list when the argument is omitted. What repair preserves both requirements?
def collect(value: int, items: list[int] | None = None) -> list[int]:
if not items:
items = []
items.append(value)
return items
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Annotation
-> str says that the function is expected to return a string to its caller.Any
Any can call a nonexistent method without a static complaint about that method.B
Black
C
Callable
Callable[[str], int] can describe a callback that counts the characters in a supplied string.CapWords
ScoreReport identifies a class that represents the results of a score calculation.Characterization test
ClassVar
ClassVar[int] counter belongs to the class, while each dataclass instance has its own declared fields.Code smell
Comment
# without becoming runtime documentation, ideally preserving a reason behind the code.Control flow
None case from later code.Covariance
Sequence[object] parameter.D
Data clump
Deep nesting
Docstring
__doc__ attribute.doctest
Duplicated code
E
Error code
arg-type indicates that a call supplies an argument of an incompatible type.Extract function
F
Final
Final name can still have an entry updated even though rebinding is rejected.Fixed-length tuple
tuple[str, int] fits a record such as ("queued", 6) in that order.Flag argument
express=True tells the reader more than an unexplained positional True.Formatter
Forward reference
G
Generic class
Stack[int] accepts integers in push and returns integers from pop.Generic function
Any.Google style
Gradual typing
Guard clause
if block.I
Identity comparison
is or is not to test whether two references identify the same object, including the None singleton.value is None handles a missing result without excluding valid zero values.Invariance
list[str] to code allowed to append any object to its input.Iterable
Iterable[str] parameter lets a joining helper accept a generator as well as a list of names.K
Keyword-only parameter
* in a signature and must be named at a call, making flags clearer while changing accepted calls.express=True explicit and requires migration of old positional calls.L
Linter
except: even after a formatter has made the code neatly aligned.Literal
Literal containing "draft" and "sent" lets a checker reject the misspelled state "send".M
Magic number
86400 with SECONDS_PER_DAY explains the time unit used in a conversion.Mapping
Mapping[str, object] parameter accepts a dictionary with string keys and integer values.Module override
Mutable default
mypy
mypy src/ checks the source directory using the project's selected typing settings.N
Named constant
EXPRESS_MULTIPLIER = 2 makes the purpose of the delivery multiplier visible.NewType
NewType for client IDs helps stop a plain integer parcel ID being passed to a client lookup.Nominal typing
Sequence.noqa
# noqa: F401 can suppress one justified unused-import finding without hiding every rule.NotRequired
NotRequired[str] note can be missing from a record, but an integer note is still a type error.O
object
object needs a string check before its body can call a string-specific method.Observable behavior
Optional value
None as well as its other declared type; this does not by itself allow an argument to be omitted.override
override catches a misspelled describ when the intended base method is named describe.P
Parameter object
Address parameter object carries street, city and postal code together to several delivery helpers.PEP 8
snake_case and classes with CapWords names.PEP 257
Primitive obsession
Protocol
Protocol with area() -> float accepts an unrelated square class that supplies that method.py.typed
py.typed so consumers can use those declarations.R
Refactoring
Rename
t to total_price wherever that variable is referenced.reveal_type
reveal_type after a branch helps explain why a method call is accepted on that path.Ruff
Rule family
I rule family enables import ordering, while B enables checks for bug-prone code patterns.Runtime-checkable protocol
read even when that method returns the wrong kind of value.S
Self
Self return lets SpecialCounter().increment() retain the type SpecialCounter for later calls.Sequence
Sequence[float] parameter can accept integer lists for a calculation that indexes its input.Side effect
snake_case
load_scores describes a function using the form expected by Python readers.Static type checker
Strict mode
Structural typing
Stub file
.pyi file, allowing static checking without including its implementation.T
Type alias
type Scores = list[int] can replace a long repeated annotation in signatures.Type argument
list[str] or the value type in a dictionary.str type argument in set[str] says that every member is expected to be a string.Type cast
str cannot make an integer support .strip() when the program later calls it.Type constraint
(str, bytes) prevents a concatenation call from mixing the two kinds of input.Type hint
customer_name: str lets a checker flag an integer assigned to that name.Type inference
[8, 12] as a list of integers when it initializes a new variable.Type narrowing
.upper() after an early return has excluded None.Type parameter
TYPE_CHECKING
if TYPE_CHECKING: can resolve a type for mypy without running a circular import.TypedDict
TypedDict can require a string title and integer year without validating newly received JSON.TypeVar
TypeVar("T", bound=Sized) supplies the older equivalent of declaring the bounded parameter T: Sized.U
Union
int or str needs narrowing before code uses operations specific to only one case.Upper bound
Sized lets a generic comparison call len on each of its arguments.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.