Skip to content

Instantly share code, notes, and snippets.

@cwells
Last active July 3, 2023 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwells/6e6dfed3a88b2944cb904461d66501ab to your computer and use it in GitHub Desktop.
Save cwells/6e6dfed3a88b2944cb904461d66501ab to your computer and use it in GitHub Desktop.
from typing import Any, TypedDict, Union
from typeguard import CollectionCheckStrategy, check_type
class TypedObject:
def __init__(self, object_type: Any) -> None:
self.object_type = object_type
def validate(self, value: Any) -> Any:
check_type(
value,
self.object_type,
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
)
return value
class TagType(TypedDict):
name: str
value: Union[str, int]
class ThingType(TypedDict):
name: str
id: int
tags: list[TagType]
thing = TypedObject(ThingType)
thing.validate( # succeeds
{
"name": "Foobar 2000",
"id": 100,
"tags": [
{"name": "industry", "value": "Foo"},
{"name": "utility", "value": "Foo preparation"},
]
}
)
thing.validate( # TypeCheckError: value of key 'id' of dict is not an instance of int
{
"name": "Foobar 2000",
"id": "100",
"tags": [
{"name": "industry", "value": "Foo"},
{"name": "utility", "value": "Foo preparation"},
]
}
)
thing.validate( # TypeCheckError: item 1 of value of key 'tags' of dict has unexpected extra key(s): "junk"
{
"name": "Foobar 2000",
"id": 100,
"tags": [
{"name": "industry", "value": "Foo"},
{"name": "utility", "value": "Foo preparation", "junk": "oogedy"},
]
}
)
@cwells
Copy link
Author

cwells commented Jul 3, 2023

https://pypi.org/project/typeguard/

Documentation is out of date, so don't try their examples.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment