Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.NamedTuple

Define an immutable tuple subclass with named, annotated fields.

Version: Python 3.14; repository image, production runtime not attested

Syntax

class Step(NamedTuple): ...

Define an immutable tuple subclass with named, annotated fields.

Field names support attribute access while their positions support unpacking and indexing. Fields with defaults must follow those without defaults, and annotations do not validate the constructor arguments.

Replacing a field returns a new tuple.

Examples

from typing import NamedTuple

class Step(NamedTuple):
    code: str
    count: int = 1

a = Step("A")
b = a._replace(count=4)
key, count = b
print(key, count, a.count, b[1])
print(type(Step("B", "four").count).__name__)

Result

A 4 1 4
str

Replacing a field returns a new tuple.

Sources