liveBook · Manning

Named tuple

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A typed named tuple is an immutable tuple-like record whose fields have names and declared types.

A named tuple combines tuple immutability with named fields. It can be accessed by index or attribute, making structured program state clearer than positional tuples while avoiding mutable dictionary keys. section 22.1.1 section 22.1.2

Create and use a named tuple in three steps:

  • Import namedtuple and define a record type: State = namedtuple('State', ['cell', 'player']). section 22.1.2
  • Instantiate it with State(1, 'X'), then read state.cell, state.player, state[0], or state[1]. section 22.1.2
  • Update it by assigning the result of state._replace(board=new_board, player='O') to a new or existing variable. section 22.1.5

Typed game state

A typing.NamedTuple class can describe a complete Tic-Tac-Toe state: class State(NamedTuple): board: List[str] = list('.' * 9); player: str = 'X'; quit: bool = False; draw: bool = False; error: Optional[str] = None; winner: Optional[str] = None. State() starts an empty game, while State(player='O') overrides one default. Type hints describe intended types, and mypy can detect misuse before runtime. section 22.1.3 section 22.4

In this last exercise, we’re going to revisit the Tic-Tac-Toe game from the previous chapter. That version played one turn of the game by accepting an initial --board and then modifying it if there were also valid options for --player and --cell. It printed the one board and the winner, if any. We’re going to extend those ideas into a version that will always start from an empty board and will play as many turns as needed to complete a game, ending with a winner or a draw.


Use the Tic-Tac-Toe state table to trace how an initially empty board changes across interactive turns. section 22.0

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines construction, indexing, named access, immutability, typed fields, defaults, and _replace(), but not implementation internals.
Examples
Uses cell-and-player records, a full Tic-Tac-Toe state, default initialization, invalid fields, and immutable turn updates.
What it assumes
Assumes basic Python and introduces tuples, immutability, named fields, and type annotations through a game-state problem.
What you can do after
Apply typed named tuples to represent state, update them with _replace(), and check type misuse with mypy.
How it connects
Connects tuples, dictionaries, TypedDict, type hints, program state, mypy, and unit testing.

Also explained in

Compare how 3 books explain named tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.