Using TypedDict with invalid attribute names

Posted 17 April 2024


I've previously covered how to use generic types for TypedDict values but another challenge you can run into when using TypedDict is in cases where a key name is not a valid identifier. In Python, identifiers (or names) are limited on the characters they can contain (generally uppercase and lowercase letters A through Z, the underscore _ and digits 0 through 9).

You'll generally use TypedDict by defining a class:

from typing import TypedDict

class Book(TypedDict):
  id: int 
  name: str

book: Book = {"id": 123, "name": "To Kill A Mockingbird"}

However this syntax doesn't work if any keys aren't valid identifiers - perhaps they contain a period . or a hyphen -:

from typing import TypedDict

class Book(TypedDict):
  id: int 
  name: str
  some-hyphen-field: str
  field.dot: str

In this case you can use the functional syntax:

from typing import TypedDict

Book = TypedDict(
  'Book',
  {
    "id": int,
    "name": str,
    "some-hyphen-field": str,
    "field.dot": str
  }
)

Related posts

Python TypedDict with Generics

Published

How to define a Python type for a dict with generic values

Mocking Boto3 with pytest

Published

Mock requests to AWS services with pytest

Configure Boto3 endpoint_url

Published

Use environment variables to point Boto3 at local services


Thanks for reading

I'm Alex O'Callaghan and this is my personal website where I write about software development and do my best to learn in public. I currently work at Mintel as a Principal Engineer working primarily with React, TypeScript & Python.

I've been leading one of our platform teams, first as an Engineering Manager and now as a Principal Engineer, maintaining a collection of shared libraries, services and a micro-frontend architecture.