Using TypedDict with invalid attribute names

Posted 17 April 2024 · 1 min read

Tags:

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
  }
)

Get new posts by email

Subscribe to get new posts to your inbox, or use the RSS feed with your own feed reader.


Related posts · browse by tag

Python TypedDict with Generics

Published · 1 min read

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

Mocking Boto3 with pytest

Published · 1 min read

Mock requests to AWS services with pytest

Configure Boto3 endpoint_url

Published · 1 min read

Use environment variables to point Boto3 at local services