typing.NamedTuple
Add type hints to named tuples.
typing.NamedTuple is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
A Typed Alternative
The typing.NamedTuple base class is a modern, class-based way to define named tuples. It adds type hints and reads like a normal class, which most editors and type checkers understand better than the factory form.
Class-Based Syntax
Subclass NamedTuple and declare each field with a type annotation. The result is still a real tuple.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(1, 2)
print(p)Same Tuple Behavior
Everything from the factory version still works: name access, index access, unpacking, and immutability.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(1, 2)
print(p.x, p[1])
x, y = p
print(x, y)Default Values Inline
Give a field a default simply by assigning a value in the class body. Defaulted fields must come after non-defaulted ones.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
z: int = 0
print(Point(1, 2))
print(Point(1, 2, 9))Adding Methods
Because it is a class, you can add real methods. This is something the collections.namedtuple factory cannot do cleanly.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
def distance_sq(self):
return self.x ** 2 + self.y ** 2
print(Point(3, 4).distance_sq())Properties Too
You can also define computed properties that derive values from the fields.
from typing import NamedTuple
class Rectangle(NamedTuple):
width: int
height: int
@property
def area(self):
return self.width * self.height
print(Rectangle(3, 4).area)Helper Methods Carry Over
The familiar tuple helpers are still available: _replace(), _asdict(), and _fields all work the same way.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(1, 2)
print(p._asdict())
print(p._replace(x=9))Type Hints Document Intent
The annotations are not enforced at runtime, but they document expected types and let tools like mypy catch mistakes before you run the program.
from typing import NamedTuple
class Employee(NamedTuple):
name: str
salary: float
active: bool = True
e = Employee('Alice', 5000.0)
print(e)NamedTuple vs Dataclass
Choosing between them:
- NamedTuple: immutable, tuple-like, supports indexing and unpacking.
- dataclass: mutable by default (or frozen), no indexing, more configuration options.
- Pick NamedTuple when tuple behavior matters; pick dataclass for richer records.
Nesting and Composition
Named tuples compose nicely. A field can be another named tuple, building structured immutable data.
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
class Line(NamedTuple):
start: Point
end: Point
line = Line(Point(0, 0), Point(3, 4))
print(line.end.y)As Function Return Types
Annotate a function to return your NamedTuple so editors know the field types of the result. The annotation documents the shape of the returned record.
from typing import NamedTuple
class Stats(NamedTuple):
minimum: int
maximum: int
def analyze(nums) -> Stats:
return Stats(min(nums), max(nums))
r = analyze([5, 2, 8])
print(r.minimum, r.maximum)Quick Check
What is an advantage of typing.NamedTuple over the collections.namedtuple factory?
Recap
You learned to add type hints to named tuples.
- Subclass
typing.NamedTuplewith annotated fields. - Set defaults inline; add methods and properties.
- Helpers
_replace,_asdict,_fieldsstill work. - Prefer it over the factory for readability and tooling.
Frequently asked questions
Is the “typing.NamedTuple” lesson free?
Yes — the full text of “typing.NamedTuple” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “typing.NamedTuple”?
Add type hints to named tuples. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “typing.NamedTuple” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Enum Class
- IntEnum and Flag
- NamedTuple Basics
- typing.NamedTuple