Rodrigo Girão Serrão: TypedDict with extra items

4 weeks ago 42
Club.noww.in

Learn how to define a TypedDict that accepts extra items of a given type.

A TypedDict is a type constructor that allows creating specialised types for dictionaries that have a fixed set of string keys:

from typing import TypedDict class Movie(TypedDict): title: str year: int

The snippet above creates a new type Movie that represents dictionaries with the key "title" and a string value, and the key "year" and an integer value:

forrest_gump = {"title": "Forrest Gump", "year": 1994}

In Python 3.15, TypedDict was improved to allow specifying whether or not the dictionary may have other keys and what must be the type of those other items when they're allowed.

15 days of Python 3.15

To celebrate the release of Python 3.15, over the next 15 business days I'll be writing about a new 3.15 feature every day. Explained clearly and with examples so you don't have to sift through the changelog.

Subscribe to receive this free email series:

Enroll for free 🐍🚀

If you want, you can also check the schedule of the upcoming emails.

Allowing extra items of a given type

When creating a TypedDict, you may specify the class parameter extra_items. When extra_items is set, your TypedDict may have additional keys of the type specified:

from typing import TypedDict class Movie(TypedDict, extra_items=str): title: str year: int

This snippet of code creates a TypedDict with two keys that allows extra string items, as specified by extra_items=str:

# ✅ Type checks m1: Movie = {"title": "Forrest Gump", "year": 1994, "genre": "Comedy/Romance"}

The assignment to m1 is type safe. While the key "genre" is not specified in the definition of Movie, the corresponding item is a...

Read Entire Article