Python Type Hints

Type Hints and Clean Code in Python

Make Python code easier to read, check and change. Add type hints to functions, collections and classes, write generic functions and protocols, and run a static type checker such as mypy to catch mistakes before the code runs. Follow the PEP 8 style guide with the help of formatters and linters such as Black and Ruff, write useful docstrings and comments, and recognize code smells. Finally, refactor small functions step by step without changing what they do.

IntermediateLesson 8 of 9 in Intermediate Python Course

What you will learn

  1. 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 do
      Read 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 values
      Describe 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 types
      Choose between Any and object, and use Callable, Literal, Final, TypedDict, NewType and type aliases to state exactly which values are allowed.
  2. 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 reports
      Run 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 gradually
      Set up mypy in pyproject.toml, raise strictness step by step, handle untyped libraries and silence errors only in a targeted way.
  3. 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 parameters
      Link 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 types
      Write generic container classes, define generic aliases, and use variance to decide which collection types to accept and return.
    • Type classes, methods and protocols
      Annotate attributes and methods, use Self and override, and describe required behavior with protocols instead of base classes.
  4. 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 naming
      Lay out and name code the way PEP 8 recommends, and know the reasoning and the limits of the guide.
    • Automate style with linters and formatters
      Use 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 comments
      Write PEP 257 docstrings in a consistent style for modules, classes and functions, and write comments that explain why rather than what.
  5. Spot the signs of hard-to-maintain code, and improve it in small, behavior-preserving steps backed by tests and tools.
    • Recognize common code smells
      Name the typical warning signs in functions and modules, and judge when a smell is worth fixing.
    • Refactor safely in small steps
      Change the structure of code without changing its behavior, using tests, tools and version control as a safety net.
    • Apply core refactorings to small functions
      Improve functions with extract function, rename, named constants, guard clauses, removal of duplication, parameter objects and clearer arguments, checking each step.

Python Type Hints study guide

5 chapters

1

Describe 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 -> None for functions without a useful return value.
  • Python accepts integers for a float parameter 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] means T | None; a default controls argument omission.
  • Use is None, isinstance or 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
HintValues acceptedOperations the checker allows
AnyAny valueAny operation, without checking it
objectAny valueOnly 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 object for arbitrary values that must still be checked before specialized operations.
  • Any allows unchecked operations and can spread through expressions.
  • Callable describes an input and output signature; Literal restricts exact values.
  • Final prevents static reassignment of a name, not mutation of its contents.
  • TypedDict assigns types to fixed keys; NotRequired allows a key to be absent.
  • A type alias renames a type; NewType creates a distinct static identity.
2

Find 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 codeWhat to inspect
assignmentA value conflicts with the receiving variable's type.
return-valueA returned expression conflicts with the return annotation.
union-attrOne possible union member lacks the attribute.
attr-definedThe known type lacks the attribute.
call-argAn argument name or argument count does not match.
returnA 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_type to inspect inference, then remove the diagnostic.
  • --check-untyped-defs checks bodies but leaves unannotated parameters as Any.
  • 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.toml and 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.typed provide library typing information; missing-import ignores introduce Any.
  • TYPE_CHECKING imports are available to static analysis, not ordinary runtime code.
3

Keep 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 typeNeeded 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, Sequence or Mapping for the reading operations a function needs.
  • Mapping is 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; ClassVar marks shared class data.
  • Self preserves the receiver type, including subclasses, in fluent method results.
  • @override helps 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.
4

Make 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
RoleConventionExample
Function, method, variablesnake_caseload_scores
ClassCapWordsScoreReport
Module constantUPPER_CASEMAX_RETRIES
Internal nameLeading underscore_parse_line
Exception classEnds in ErrorInvalidScoreError

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 None and 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 familyPurposeExample finding
E, WStyle conventionsE711: == None
FLikely code errorsF401: unused import
IImport orderingI001: unsorted imports
BBug-prone patternsB006: mutable default
NNamingN802: function name
UPModern syntaxUP006: old collection alias
DDocstringsConvention-dependent documentation checks
C90ComplexityC901: too many paths
ANNAnnotationsMissing 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 None and 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.
5

Improve 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 callObserved 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

5 Walkthroughs

1

Make a data path readable to a checker

16 steps
Annotate a function, handle a missing result and choose precise types for records, callbacks and identifiers.
  1. 1
    IntroductionFollow 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.

  2. 2
    ExplanationRead the function boundary
    def greet(name: str, times: int = 1) -> str:
        return ("Hello, " + name + "! ") * times
    

    name expects a string; times expects an integer and defaults to 1. 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.

  3. 3
    ExampleAn 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.

  4. 4
    ChallengeDecide what the hint changes

    A function is declared def half(value: float) -> float:. Can a checker accept half(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.

  5. 5
    ExplanationMatch 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], not list[int, str].

    A tuple can describe separate positions. tuple[str, int] fixes the order and length; tuple[int, ...] allows any number of integers.

  6. 6
    ExampleKeep 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 of str | None.

    Neither form lets a caller omit user_id. A default controls omission; a union controls the values an argument or result may hold.

  7. 7
    ExampleNarrow 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 for None can 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.

  8. 8
    ChallengeHandle 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 int and returns. Only the string case reaches the final line.

  9. 9
    Key InsightChoose how much checking to keep

    Both Any and object can receive arbitrary values. Their operations differ: Any permits unchecked method calls, while object requires proof before a specialized method is used.

    For a function that accepts unknown data and inspects it, object keeps the need for a check visible. Using Any to quiet an error can also hide later errors because expressions derived from it often stay unchecked.

  10. 10
    ExampleDescribe 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 * 2 with 5 gives 10.

    Passing len fails the contract: integers do not have the length operation its input requires. A callable hint describes both sides of the call.

  11. 11
    ExplanationState choices and stable names

    Literal["r", "w"] restricts a parameter to those exact values. A checker can reject "x" before the call runs. Use an Enum when a richer collection of named choices is helpful.

    MAX_RETRIES: Final = 3 prevents reassignment in static checking. Final protects the name, not the contents of a mutable object, and Python itself does not enforce the declaration.

  12. 12
    ExampleType 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 Movie does not inspect or repair the incoming values.

  13. 13
    ConnectionSeparate an alias from an identity

    type Vector = list[float] gives a type a convenient name. An ordinary float list can be used wherever Vector is expected.

    UserId = NewType("UserId", int) creates a distinct static identity. A UserId parameter accepts UserId(42) but rejects a plain 42 in static checking. The wrapper returns the same integer at runtime and adds no range or ownership validation.

  14. 14
    ChallengeKeep a missing field distinct from None

    A TypedDict declares comment: NotRequired[str]. A record omits the key; another contains "comment": None. Are both statically valid?

    ---reveal---

    Only the omitted key is valid. NotRequired permits absence, while str still controls the value when the key is present. To permit a present None, the field's value type would also need to include None.

  15. 15
    ChallengeRepair 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.

  16. 16
    RecapRead 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.

2

Use checker reports to improve a project

12 steps
Run mypy, trace a report to its cause and add repeatable settings without hiding unchecked boundaries.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn a report into a useful edit
  2. 2
    ExplanationRun the checker in the active environment
  3. 3
    ExampleFind the source of an argument mismatch
  4. 4
    ExampleComplete the empty-input path
  5. 5
    TipInspect inference and checking coverage
  6. 6
    ChallengeFollow the branch behind a report
  7. 7
    ExplanationApply strictness where the code is ready
  8. 8
    Key InsightA cast is a claim to the checker
  9. 9
    ConnectionFind the missing library information
  10. 10
    TipImport types without importing runtime code
  11. 11
    ChallengeRepair a boundary and keep the check useful
  12. 12
    RecapCombine static evidence with behavior checks
3

Preserve types as code becomes reusable

16 steps
Build generic functions and a stack, choose reading interfaces and check a protocol-based object contract.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionReuse an operation without losing its types
  2. 2
    ExplanationLink the input element to the result
  3. 3
    ExampleGive a generic body a needed operation
  4. 4
    ChallengeChoose one permitted type for a call
  5. 5
    ExampleConnect a stack’s storage and methods
  6. 6
    Key InsightA writable list cannot widen safely
  7. 7
    TipRequest the operations the body uses
  8. 8
    ChallengeMake a read-only helper flexible
  9. 9
    ConnectionA callback’s inputs and result both matter
  10. 10
    ExplanationDescribe instance data and shared data
  11. 11
    ExampleDeclare the behavior an area calculation needs
  12. 12
    ExampleUse the shared behavior
  13. 13
    ChallengeKeep inherited callers working
  14. 14
    Key InsightMember checks and ancestry checks differ
  15. 15
    ChallengeCombine a precise result with a behavior contract
  16. 16
    RecapKeep the promise callers depend on
4

Set up code that is easy to read

13 steps
Apply Python layout conventions, separate formatting from linting and write documentation that callers can use.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the next reading easier
  2. 2
    ExplanationMake structure visible
  3. 3
    ExampleShow a name’s role
  4. 4
    ChallengeKeep zero in a valid data path
  5. 5
    ExplanationSeparate layout from findings
  6. 6
    ExampleRead rule codes as clues
  7. 7
    ExampleCreate the omitted-argument list inside
  8. 8
    ChallengeChoose the check that finds the problem
  9. 9
    ExplanationMake documentation discoverable
  10. 10
    ExampleExplain the caller’s units and limits
  11. 11
    ChallengePut a reason in the comment
  12. 12
    ChallengeProtect behavior while improving the description
  13. 13
    RecapGive each quality tool a clear job
5

Refactor a calculation in verified steps

15 steps
Find useful improvements, record shipping behavior and flatten the calculation before migrating its interface.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionImprove one difficulty at a time
  2. 2
    ExampleRead the repeated delivery cases
  3. 3
    ExplanationUse smells as investigation clues
  4. 4
    ChallengeChoose a useful improvement
  5. 5
    ExampleRecord the normal shipping cases
  6. 6
    Key InsightBehavior reaches beyond the usual result
  7. 7
    ChallengeFind the gap in a passing test
  8. 8
    ExampleMove the invalid case out first
  9. 9
    ExampleChoose rates before calculating
  10. 10
    ExampleApply express to the weight charge
  11. 11
    ChallengeCheck the shared formula in a new case
  12. 12
    ConnectionSeparate clearer choices from a new interface
  13. 13
    TipChoose names that remove explanation work
  14. 14
    ChallengePlan the next change after checks pass
  15. 15
    RecapKeep each verified change understandable

Python Type Hints practice questions

50 Practice Questions in 5 sets

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"
  1. An integer equal to 17.
  2. A string containing "17".
  3. The integer type object, int.
  4. No value, because the hint rejects it.
Show answerHide answer
Answer: B
The assignment stores the string "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

A function has the signature def badge(name: str | None) -> str:. A caller wants to omit the argument and receive the missing-name behavior. What signature change allows that?
  1. Use name: str with no default.
  2. Use name: str = None.
  3. Use name: Optional[str] with no default.
  4. Use name: str | None = None.
Show answerHide answer
Answer: D
A default allows the argument to be omitted, and 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

A function accepts any Python value but must check its type before calling a string-specific method. What parameter hint expresses that requirement?
  1. object
  2. Any
  3. str
  4. None
Show answerHide answer
Answer: A
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.

  1. Add return None after the if block.
  2. Change only the parameter to list[float].
  3. Add return 0 after the if block.
  4. Add # type: ignore[arg-type] to max.
Show answerHide answer
Answer: C
The empty-list path currently falls off the end and returns 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

A project must find type-ignore comments that no longer suppress an error. What mypy setting enables that check?
  1. ignore_missing_imports = true
  2. warn_unused_ignores = true
  3. disallow_any_generics = true
  4. python_version = "3.12"
Show answerHide answer
Answer: B
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]
  1. Sequence[float]
  2. Any
  3. float
  4. int | float
Show answerHide answer
Answer: C
The tuple supplies float elements, so the checker binds 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
  1. Sequence[float]
  2. Iterable[float]
  3. list[int | float]
  4. Sequence[object]
Show answerHide answer
Answer: A
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

A lookup returns int | None, and zero is a valid count. What test enters the missing-value branch without treating zero as missing?
  1. if not count:
  2. if count == False:
  3. if count is not None:
  4. if count is None:
Show answerHide answer
Answer: D
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

A function takes 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?
  1. Repeat the signature and list the type names.
  2. Explain the output units and the duration restriction.
  3. Describe every assignment in execution order.
  4. List only the local variable naming choices.
Show answerHide answer
Answer: B
The caller needs the units and restriction to supply meaningful data and interpret the result. The exception condition belongs with that interface information. Repeating float from the signature adds less value and still leaves the meaning of the returned number unclear.

Question 10 of 10

Two helpers both accept 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?
  1. Group the address fields in an Address dataclass.
  2. Group all four values in an unnamed tuple.
  3. Make every parameter an optional string.
  4. Copy each helper for each city it serves.
Show answerHide answer
Answer: A
The three address fields form a data clump, and a named parameter object keeps their roles together across both helpers. Weight stays separate because it is not part of that address group. An unnamed tuple keeps the positional ambiguity that caused the swapped-field calls.
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

A helper prints a progress message and falls off the end. What return annotation describes its lack of a useful result?
  1. -> str
  2. -> bool
  3. -> None
  4. -> object
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()
  1. An empty string.
  2. The string "missing".
  3. The value None.
  4. It raises AttributeError.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A program has 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?
  1. Both are accepted statically; wrapping validates the ID range.
  2. The first is accepted statically; wrapping creates an integer subclass.
  3. Both are rejected statically; an alias cannot enter a NewType.
  4. The first is rejected statically; wrapping leaves the integer unchanged.
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
  1. It skips string expressions; enable --warn-return-any.
  2. It skips unannotated bodies; enable --check-untyped-defs.
  3. It executes no imports; enable --ignore-missing-imports.
  4. It accepts all additions; enable --disallow-any-generics.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A protocol requires 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?
  1. No; it must explicitly inherit from the protocol class.
  2. Yes; its compatible method satisfies the structural contract.
  3. Yes; only the method name matters to static checking.
  4. No; protocols can describe attributes but not methods.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A function loads score data. How should its name be written under PEP 8?
  1. Lowercase words separated by underscores.
  2. Capitalized words joined without underscores.
  3. Uppercase words separated by underscores.
  4. Lowercase first word with later capitals.
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?
  1. Increase the formatter line length and format the file again.
  2. Treat the handler as safe because formatting completed.
  3. Rename the function so the handler has a clearer traceback.
  4. Lint and choose a handler for the exceptions the code can handle.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

The expression elapsed_s / 86400 appears in several functions, all converting seconds to days. What focused change clarifies the repeated literal?
  1. Replace every numeric literal with a separate helper function.
  2. Copy the expression into a new branch for each caller.
  3. Define SECONDS_PER_DAY = 24 * 60 * 60 and use that name.
  4. Change the number to a string so its digits are explicit.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An old function appends to a supplied list and returns its length. A rewrite copies that list, appends to the copy and returns the same length. Tests assert only the returned length and still pass. What behavior did the tests fail to protect?
  1. The static type of the copied list.
  2. The length of its parameter list.
  3. The spelling of its local variables.
  4. Mutation of the caller-owned list.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A fee is 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?
  1. Express stays 19 because multiplication distributes over the weight.
  2. Standard changes from 13 to 26 because the rate is doubled.
  3. Express changes from 19 to 26 because the base fee is also doubled.
  4. Standard stays 19 because the base fee is paid once.
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

What annotation describes exactly a label followed by a count, such as ("ready", 9)?
  1. tuple[str, int]
  2. tuple[str | int, ...]
  3. list[str, int]
  4. tuple[int, str]
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A 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?
  1. return record["note"].upper()
  2. return str(record.get("note")).upper()
  3. return record.get("note", "").upper()
  4. return record.get("note", None).upper()
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For value: int | str, the function returns from the isinstance(value, int) branch. What does a checker know about value on the next reachable line?
  1. It is still int | str.
  2. It is a str.
  3. It becomes Any.
  4. It is an int.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A library is installed and runs correctly, but mypy reports missing stubs. The maintainer publishes a compatible types-... package. What should the project do before suppressing the import report?
  1. Set every module to ignore_missing_imports = true.
  2. Cast every imported function result to object.
  3. Run the formatter to rewrite the library imports.
  4. Install the matching stub package in the checking environment.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A function must concatenate either two strings or two byte strings and keep the corresponding result type. What signature rules out a mixed call while preserving that relationship?
  1. def join(a: str | bytes, b: str | bytes) -> str | bytes:
  2. def join[S: (str, bytes)](a: S, b: S) -> S:
  3. def join[T](a: T, b: T) -> T:
  4. def join(a: object, b: object) -> object:
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A function expects Mapping[str, object]. Another expects Mapping[object, int]. With rows: dict[str, int], which calls are statically compatible?
  1. Only the call expecting Mapping[object, int].
  2. Both calls accept the same dictionary type.
  3. Only the call expecting Mapping[str, object].
  4. Neither call accepts a concrete dictionary.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A method returning self is inherited by SpecialCounter. What return annotation preserves SpecialCounter in SpecialCounter().reset()?
  1. Self
  2. Counter
  3. object
  4. None
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Ruff reports B006 on a function whose default list is appended to. What lifetime causes this warning?
  1. A new default list is created whenever the function is called.
  2. The default list is copied whenever an argument is omitted.
  3. The default list is cleared when a return statement executes.
  4. The default list is created once when the function is defined.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A public normalize(values: list[str]) -> None strips whitespace in the supplied list itself. What caller-relevant fact should its docstring make clear?
  1. The call changes the supplied list in place.
  2. The call internally uses a loop index.
  3. The return type has the spelling None.
  4. The implementation names its input values.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An old function uses 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?
  1. Another positive weight with a known local region.
  2. An unknown region string, checking its result or exception.
  3. Another positive weight with a known remote region.
  4. A known region passed through a renamed local variable.
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

On Python 3.12 without future annotations, a method inside class Link declares -> Link before the class name has been bound. What annotation spelling avoids that immediate lookup?
  1. -> type(Link)
  2. -> Link()
  3. -> [Link]
  4. -> "Link"
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A function receives 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?
  1. Return for false values, uppercase remaining values, then increment.
  2. Return for None, return for isinstance(value, int), then uppercase.
  3. Return for None, uppercase remaining values, then check for integers.
  4. Return for isinstance(value, str), then increment all remaining values.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A checker error disappears after 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?
  1. Use isinstance(raw, str) and handle the non-string path.
  2. Keep the cast and add a more specific type-ignore code.
  3. Change the cast target to Any before calling .strip().
  4. Annotate the receiving variable str again before the call.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A generic helper compares len(a) and len(b) and returns one argument. What upper bound allows the length calls while keeping the selected argument's type?
  1. T: int
  2. T: object
  3. T: Sized
  4. T: Callable
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A runner calls a callback with an 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?
  1. read_object: it accepts every promised input and returns int.
  2. read_text: its narrower input and integer result meet the contract.
  3. describe: its integer input allows its string result to be used.
  4. All three: each matches at least one part of the required signature.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A runtime-checkable protocol requires read() -> bytes. An unrelated object has read() -> str. Why can an instance check succeed while static assignment to the protocol is rejected?
  1. The runtime check checks bytes conversion; the checker checks inheritance.
  2. The runtime check sees the member; the checker also checks its result type.
  3. The runtime check accepts every object; the checker checks method names only.
  4. The runtime check ignores members; the checker evaluates the method body.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A project uses Black with 88-character lines, while a contributor notes that PEP 8 recommends 79. What should a routine edit follow?
  1. A personal 79-character override applied only to new lines.
  2. A new 99-character limit applied to the whole project.
  3. The widest line already present, regardless of configuration.
  4. The project’s established 88-character formatting setting.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A project selects Ruff families E, F and B. It wants import ordering checked automatically too. What configuration change addresses that need?
  1. Set the formatter line length to 79.
  2. Add ANN to the selected lint families.
  3. Add I to the selected lint families.
  4. Suppress F401 for the entire project.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

An old function is called as 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?
  1. Update only the positional call; keyword calls ignore parameter renaming.
  2. Update both calls for the renamed, reordered and keyword-only parameters.
  3. Update only the keyword call; positional calls automatically follow names.
  4. Update neither call; type annotations preserve the old calling convention.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An original guard runs a calculation only when 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?
  1. if not score > 0: raise ValueError
  2. if score <= 0: raise ValueError
  3. if not score: raise ValueError
  4. if score < 0: raise ValueError
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

A module defines RATES: Final = {"near": 1.2}. How does Final affect RATES = {} and RATES["near"] = 1.4 under static checking?
  1. It rejects both rebinding the name and changing any dictionary entry.
  2. It rejects rebinding the name but permits changing the dictionary entry.
  3. It permits rebinding the name but rejects changing the dictionary entry.
  4. It rejects neither operation because dictionaries cannot use Final.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A report ends with [arg-type] and says an argument is str where int is expected. What should you inspect first?
  1. The receiving function’s declared return type.
  2. The types of unrelated local variables.
  3. The reported call and the receiving parameter type.
  4. The number and names of the supplied arguments.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A project must require complete hints in service.core.*, leave legacy modules under default rules and detect stale ignores everywhere. What configuration fits all three needs?
  1. Global warn_unused_ignores, plus a core override with disallow_untyped_defs.
  2. Global strict, plus a core override with ignore_missing_imports.
  3. Global ignore_missing_imports, plus a core override with strict only.
  4. Global disallow_untyped_defs, plus a core override with unused-ignore warnings.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An integer-only caller uses 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?
  1. Use def take(items: Sequence[object]) -> object: with the same body.
  2. Use def take(items: Sequence[Any]) -> Any: with the same body.
  3. Use def take(items: Sequence[int | str]) -> int: with the same body.
  4. Use def take[T](items: Sequence[T]) -> T: with the same indexing body.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A base method is 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?
  1. It widens text to object, so it no longer accepts every base input.
  2. It permits positional overwrite, so keyword calls no longer work.
  3. It makes overwrite required, so a valid base call can lack an argument.
  4. It adds a defaulted path, so every caller must supply a path argument.
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}"
  1. The string is not the first statement in the function.
  2. The string uses triple quotes instead of one pair.
  3. The function also contains a return statement.
  4. The function has an annotated integer parameter.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A 26-line function performs one clear calculation, has meaningful names and no duplicated logic. A proposal splits each arithmetic line into a helper named step1, step2 and so on. What is the strongest reason to reject the proposal as described?
  1. Every function under 30 lines must remain unchanged.
  2. Arithmetic expressions can never be extracted into helpers.
  3. A linter can decide every function boundary automatically.
  4. The helpers add navigation without naming useful separate purposes.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Both routines receive an empty log. 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?
  1. Both raise ValueError, and both leave the log empty.
  2. Both raise ValueError, but only the rewrite leaves "saved" in the log.
  3. Only the rewrite raises ValueError, and it leaves "saved" in the log.
  4. Both raise ValueError, but only the old routine leaves "saved" in the log.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Tests pass after changing a lookup helper from returning 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?
  1. Remove None from the return hint and accept the tests as sufficient.
  2. Cast every call result to str and suppress the remaining reports.
  3. Restore or deliberately specify the missing-key behavior and test that path.
  4. Add another present-key test with a different string result.
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
  1. Change the guard to if items is None:.
  2. Change the default to items: list[int] = [].
  3. Copy items into a new list before every append.
  4. Change the guard to if items == []:.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

81 Key Terms, each with its definition

A

Annotation
An annotation is type-related information attached to a parameter, return or variable; Python does not enforce its type claim at runtime.
The annotation -> str says that the function is expected to return a string to its caller.
Any
Any is a type that permits unchecked operations and assignments, allowing unknown type information to pass through expressions.
A value typed Any can call a nonexistent method without a static complaint about that method.

B

Black
Black is a Python formatter with few configuration choices that applies consistent layout, using an 88-character default line length.
Black's check mode reports formatting differences without rewriting the source during an automated run.

C

Callable
A Callable annotation describes the parameter types and return type a function-like value must support at a call site.
Callable[[str], int] can describe a callback that counts the characters in a supplied string.
CapWords
The naming form CapWords begins each joined word with a capital letter and is the usual convention for Python class names.
The CapWords name ScoreReport identifies a class that represents the results of a score calculation.
Characterization test
A characterization test records what existing code does before a structural edit, including behavior that may not yet be documented.
A characterization test can capture the old fallback for an unknown region before a lookup-table rewrite.
ClassVar
A ClassVar annotation marks class-level data instead of an instance field and prevents dataclasses from treating it as a field.
A ClassVar[int] counter belongs to the class, while each dataclass instance has its own declared fields.
Code smell
A code smell is a visible sign that code may be difficult to understand or maintain, inviting investigation instead of proving a bug.
A code smell such as repeated formulas matters when a future rate change would require editing every copy.
Comment
A comment adds human-readable explanation after # without becoming runtime documentation, ideally preserving a reason behind the code.
A comment can explain that an external service numbers its pages from 1, clarifying an otherwise odd offset.
Control flow
Control flow is the set of paths execution can take through branches, loops, returns and exceptions in a program.
mypy follows control flow to see that an early return removes the None case from later code.
Covariance
Covariance allows a compatible narrower value type to be substituted through a generic interface, such as a read-only sequence.
Sequence covariance lets a string list be read through a Sequence[object] parameter.

D

Data clump
A data clump is a group of related values repeatedly passed or stored together, suggesting one object with named fields.
An address data clump can become a dataclass instead of three string arguments passed through many helpers.
Deep nesting
Deep nesting places conditionals or loops inside other blocks so readers must track several active conditions at the same time.
Deep nesting in a shipping function can hide its main calculation behind several special-case checks.
Docstring
A docstring is a first-statement string literal in a module, class, function or method, stored in the object's __doc__ attribute.
A docstring can tell callers that a weight is in kilograms and must be positive before calculation.
doctest
The module doctest executes interactive-session examples embedded in documentation and compares their output with the stated results.
Running doctest can catch a docstring example whose displayed shipping cost became stale after an edit.
Duplicated code
Duplicated code repeats logic in multiple places, creating a risk that a future change updates one copy but misses another.
Duplicated code for four delivery cases can leave one case using an old rate after a price update.

E

Error code
An error code identifies a category of checker finding so it can be understood, configured or narrowly suppressed by name.
The error code arg-type indicates that a call supplies an argument of an incompatible type.
Extract function
The extract function refactoring moves a coherent block into a named helper so its purpose is visible and can be reused clearly.
Extract function can separate a mean calculation from the report that formats and prints its result.

F

Final
A Final annotation tells a checker that a name must not be reassigned; it does not make the referenced object immutable.
A dictionary held in a Final name can still have an entry updated even though rebinding is rejected.
Fixed-length tuple
A fixed-length tuple annotation gives one type for each position, specifying both the item order and the exact number of items.
A fixed-length tuple tuple[str, int] fits a record such as ("queued", 6) in that order.
Flag argument
A flag argument is a Boolean parameter that selects behavior, often making a positional call's meaning difficult to see.
A flag argument passed as express=True tells the reader more than an unexplained positional True.
Formatter
A formatter rewrites code layout consistently, handling choices such as spaces, line breaks, quotes and trailing commas.
A formatter can tidy a function's spacing while leaving its shared mutable default unchanged.
Forward reference
A forward reference names a type before its definition is available, often using a quoted name to avoid an immediate runtime lookup.
On Python 3.12, a quoted forward reference lets a method name its enclosing class in its return hint.

G

Generic class
A generic class uses type parameters to connect the types of its instance data and methods for each chosen specialization.
A generic class Stack[int] accepts integers in push and returns integers from pop.
Generic function
A generic function uses type parameters to support multiple types while preserving useful relationships in its input and output types.
A generic function returning a sequence element need not discard that element's type as Any.
Google style
Google style organizes docstrings into sections such as Args, Returns and Raises to explain the callable interface.
A Google style docstring can put an input restriction beside its argument and describe the resulting error.
Gradual typing
Gradual typing lets annotated and unannotated code coexist so a project can add static checking one useful boundary at a time.
Gradual typing lets a team annotate its public functions before working through private helpers.
Guard clause
A guard clause handles an invalid or special case with an early return or raise, leaving the main path less deeply nested.
A guard clause rejecting invalid weight lets the calculation move out of an enclosing if block.

I

Identity comparison
An identity comparison uses is or is not to test whether two references identify the same object, including the None singleton.
The identity comparison value is None handles a missing result without excluding valid zero values.
Invariance
Invariance prevents substituting a container with a different element type, protecting a mutable collection from incompatible writes.
List invariance blocks passing list[str] to code allowed to append any object to its input.
Iterable
An Iterable supplies iteration over elements and is a suitable parameter interface when code only needs to loop over its input.
An Iterable[str] parameter lets a joining helper accept a generator as well as a list of names.

K

Keyword-only parameter
A keyword-only parameter follows * in a signature and must be named at a call, making flags clearer while changing accepted calls.
A keyword-only parameter makes express=True explicit and requires migration of old positional calls.

L

Linter
A linter inspects source code for likely bugs or style problems, reporting findings that may need automatic fixes or human judgment.
A linter can flag a bare except: even after a formatter has made the code neatly aligned.
Literal
A Literal type restricts a value to listed exact constants, letting a checker enforce a small fixed set of choices.
A Literal containing "draft" and "sent" lets a checker reject the misspelled state "send".

M

Magic number
A magic number is a literal whose role is unclear from its spelling, making a meaningful constant name useful to readers.
Replacing the magic number 86400 with SECONDS_PER_DAY explains the time unit used in a conversion.
Mapping
A Mapping supplies read access to keys and values, with covariance in its value type and invariance in its key type.
A Mapping[str, object] parameter accepts a dictionary with string keys and integer values.
Module override
A module override applies selected checker settings to named modules so their checking policy can differ from the project default.
A module override can require complete annotations in a core package while legacy code stays gradual.
Mutable default
A mutable default is a changeable parameter default created at definition time and reused by calls that omit that argument.
A mutable default list retains an appended item for the next call unless a fresh list is created inside.
mypy
mypy is a Python static type checker that reports typed-code mismatches and can apply stricter checks through project configuration.
Running mypy src/ checks the source directory using the project's selected typing settings.

N

Named constant
A named constant gives a stable meaning to a value, usually with an uppercase module-level name and optionally a Final annotation.
A named constant EXPRESS_MULTIPLIER = 2 makes the purpose of the delivery multiplier visible.
NewType
A NewType creates a distinct static identity based on an existing type, while explicit wrapping returns the runtime value unchanged.
A NewType for client IDs helps stop a plain integer parcel ID being passed to a client lookup.
Nominal typing
Nominal typing determines a class relationship through declared ancestry, so similar member names alone do not establish membership.
Under nominal typing, defining indexing and length methods alone does not make a class a Sequence.
noqa
A noqa comment suppresses Ruff findings on a line; naming a specific code keeps unrelated findings on that line visible.
The comment # noqa: F401 can suppress one justified unused-import finding without hiding every rule.
NotRequired
A NotRequired field in a TypedDict may be absent, while any value present under that key must still match its declared type.
A NotRequired[str] note can be missing from a record, but an integer note is still a type error.

O

object
The type object accepts every Python value while permitting only common object operations until the value is narrowed.
A parameter typed object needs a string check before its body can call a string-specific method.
Observable behavior
Observable behavior includes results, exceptions, output, mutations, side-effect order and the interface accepted by a function.
Changing which list gets mutated alters observable behavior even if the returned length stays equal.
Optional value
An optional value can be None as well as its other declared type; this does not by itself allow an argument to be omitted.
The optional value returned by a dictionary lookup needs a missing-result branch before string use.
override
The decorator override marks a method intended to replace a base method so a checker can report a missing base match or bad signature.
Using override catches a misspelled describ when the intended base method is named describe.

P

Parameter object
A parameter object groups related arguments in one typed value with named fields, reducing repeated positional groups across interfaces.
An Address parameter object carries street, city and postal code together to several delivery helpers.
PEP 8
PEP 8 is Python's style guide, giving conventions for layout, names and code expressions while prioritizing project consistency.
PEP 8 helps a reader recognize functions in snake_case and classes with CapWords names.
PEP 257
PEP 257 defines Python docstring conventions, including triple double quotes, a command-style summary and multi-line spacing.
Following PEP 257 puts a blank line between a function's summary sentence and its detailed argument notes.
Primitive obsession
Primitive obsession uses plain strings or numbers where meaningful choices, identities or grouped values deserve an explicit type.
Primitive obsession can leave zone names unchecked as plain strings even when a program supports only two zones.
Protocol
A Protocol defines typed members required from an object without requiring the object's class to inherit from that protocol.
A Protocol with area() -> float accepts an unrelated square class that supplies that method.
py.typed
The py.typed marker tells type checkers that an installed package supplies typing information intended for use by its consumers.
A library shipping inline annotations includes py.typed so consumers can use those declarations.

R

Refactoring
Refactoring changes code's internal structure while preserving the observable behavior that existing callers can depend on.
A refactoring can flatten nested branches while keeping results, exceptions and accepted calls unchanged.
Rename
The rename refactoring changes an identifier to reveal its purpose while updating references so existing behavior is preserved.
An editor-assisted rename changes t to total_price wherever that variable is referenced.
reveal_type
The diagnostic reveal_type asks a checker to display the inferred type of an expression at a particular place in the code.
Using reveal_type after a branch helps explain why a method call is accepted on that path.
Ruff
Ruff provides a Python linter with many rule families and a separate formatter, configured through project settings.
Ruff can check imports, bug-prone patterns and modern syntax when those rule families are enabled.
Rule family
A rule family groups related lint findings under a code prefix, making the project's selected checks easier to configure and recognize.
The I rule family enables import ordering, while B enables checks for bug-prone code patterns.
Runtime-checkable protocol
A runtime-checkable protocol supports instance checks for member presence without validating full method signatures or result types.
A runtime-checkable protocol can find read even when that method returns the wrong kind of value.

S

Self
Self represents the type of a method's receiver, preserving a subclass type when an inherited fluent method returns the instance.
A Self return lets SpecialCounter().increment() retain the type SpecialCounter for later calls.
Sequence
A Sequence supplies indexed reading and length, making it useful when code needs those operations without mutating a container.
A Sequence[float] parameter can accept integer lists for a calculation that indexes its input.
Side effect
A side effect is an observable action beyond returning a value, such as changing supplied data, printing or writing a record.
Appending to a caller's list is a side effect that a refactoring's tests should check explicitly.
snake_case
The naming form snake_case uses lowercase words separated by underscores and is conventional for Python functions, methods and variables.
The snake_case name load_scores describes a function using the form expected by Python readers.
Static type checker
A static type checker analyzes source without running it and reports conflicts with the types declared or inferred for values.
A static type checker reports a string passed to an integer parameter before that call runs.
Strict mode
Strict mode enables a group of stronger checker requirements, such as complete function annotations and warnings about unused ignores.
A project can use strict mode for new code once its function boundaries are fully annotated.
Structural typing
Structural typing determines compatibility from the typed members an object provides, allowing unrelated classes to share a contract.
Structural typing accepts a class with the required protocol methods even without protocol inheritance.
Stub file
A stub file supplies a module's type signatures in a .pyi file, allowing static checking without including its implementation.
A stub file from an installed typing package lets mypy check calls into a third-party library.

T

Type alias
A type alias gives an existing type expression another name without making a distinct type or adding runtime validation.
The type alias type Scores = list[int] can replace a long repeated annotation in signatures.
Type argument
A type argument is a type supplied to a generic type, such as the element type in list[str] or the value type in a dictionary.
The str type argument in set[str] says that every member is expected to be a string.
Type cast
A type cast in Python typing asserts a type to a checker without testing, converting or copying the value at runtime.
A type cast to str cannot make an integer support .strip() when the program later calls it.
Type constraint
A type constraint limits a parameter to one of listed types for a call, connecting all positions that use the same parameter.
The type constraint (str, bytes) prevents a concatenation call from mixing the two kinds of input.
Type hint
A type hint states the type a value is expected to have, giving readers, editors and static checkers information about the code.
A type hint on customer_name: str lets a checker flag an integer assigned to that name.
Type inference
Type inference is a checker's deduction of a value's type from code, without an explicit annotation on every name.
Type inference identifies [8, 12] as a list of integers when it initializes a new variable.
Type narrowing
Type narrowing reduces the possible types of a value after a condition or control-flow step establishes which cases remain.
Type narrowing lets a checker accept .upper() after an early return has excluded None.
Type parameter
A type parameter represents a type chosen for a generic use and links occurrences of that type across inputs, storage or results.
A type parameter keeps the element returned by a generic function an integer when the caller supplies integer elements.
TYPE_CHECKING
The constant TYPE_CHECKING is true during static analysis and false during ordinary execution, enabling annotation-only imports.
An import inside if TYPE_CHECKING: can resolve a type for mypy without running a circular import.
TypedDict
A TypedDict describes fixed string keys and their individual value types while remaining an ordinary dictionary at runtime.
A TypedDict can require a string title and integer year without validating newly received JSON.
TypeVar
TypeVar declares a type variable in older generic syntax, with optional bounds or constraints linking later annotation positions.
TypeVar("T", bound=Sized) supplies the older equivalent of declaring the bounded parameter T: Sized.

U

Union
A union describes a value that may have any one of several types, requiring code to handle the relevant alternatives safely.
The union int or str needs narrowing before code uses operations specific to only one case.
Upper bound
An upper bound limits a type parameter to a specified type and its subtypes, making that type's supported operations available.
An upper bound of Sized lets a generic comparison call len on each of its arguments.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started