Skip to content

Add support for extra_items in TypedDict #538

@munkybutt

Description

@munkybutt

Things to check first

  • I have searched the existing issues and didn't find my feature already requested there

Feature description

To allow for TypedDicts with arbitrary other keys of a given type, it is possible to provide the extra_items argument:
https://typing.python.org/en/latest/spec/glossary.html#term-extra-items
Unfortunately running a check_type raises an error:

import typing_extensions
import typeguard


T_ExtraItems = str | int | float | list[str] | bool


class Test(typing_extensions.TypedDict, extra_items=T_ExtraItems):
    attrib_1: str


test: Test = {"attrib_1": "1", "attrib_2": 2}


typeguard.check_type(test, Test)  # < is technically valid due to extra_items argument
>> typeguard.TypeCheckError: dict has unexpected extra key(s): "attrib_2"

Use case

I am checking the type of a dict made up of attributes on a server.
This check runs on various versions of the software and it errors every time I add/remove/edit an attribute on the server as the keys/values no longer match.

I would like to have the check for the code that needs to access a given attribute, and if that attribute doesn't exist in the TypedDict type then it is added when it is needed.
As it stands modifying the server attributes has to be done after updating the TypedDict signature and distributing it to all users which is not ideal, especially for testing new attributes.

For now the work around I use is typing.cast but obviously is not actually checking the type 🥲

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions