liveBook · Manning

Type hints

As explained in Build Financial Software with Generative AI (From Scratch)

A type hint is optional type information attached to program elements to document or support expected value types.

Type hints annotate Python values, parameters, and returns with expected types. Python still uses duck typing and does not enforce these hints at runtime, but they document intent, make unfamiliar code easier to maintain, and support static checking. section 2.7.2

Clarify a balance-formatting function

A balance formatter can declare its input as str and its return as str: def print_balance(current_balance: str) -> str. Returning the formatted value rather than printing it lets a caller print it, write it to a file, or use it in an API response. section 1.5.2

Hints are especially useful when a dictionary selects parser functions. Without them, it can be unclear whether dictionary values are callable or which arguments they accept. A Callable annotation records that each selected parser receives one string and returns a dictionary of strings. section 2.7.1 section 2.7.2

parser_functions: Dict[str, Callable[[str], Dict[str, str]]] = {

This annotation compactly describes both sides of a dispatch table: string record-type keys and callable parser values with a declared input and result. section 2.7.2

Use hints to make an evolving application safer to navigate:

  • Annotate function parameters and return values so callers can see the intended contract. section 1.5.2
  • Add static checking with mypy, Pyright, or Pyre when a project needs stronger feedback than runtime duck typing provides. section 2.7.2

How Build Financial Software with Generative AI (From Scratch) covers it

How deep it goes
Defines annotations, contrasts duck typing with static checking, and works through Callable, Dict, parameter, and return signatures.
Examples
Uses a current-balance formatting function and a dictionary mapping payment record types to parser functions.
What it assumes
Explains annotations for readers with varying Python experience while assuming familiarity with functions and dictionaries.
What you can do after
Apply it via mypy, Pyright, or Pyre to statically check annotated Python code.
How it connects
Connects type hints to duck typing, static type checking, dictionary dispatch, Callable, and match statements.

Also explained in

Compare how 17 books explain type hints →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Financial Software with Generative AI (From Scratch). The section links point to the parts of the book it draws on.