Last active
July 3, 2023 18:48
-
-
Save cwells/6e6dfed3a88b2944cb904461d66501ab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}, | |
] | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://pypi.org/project/typeguard/
Documentation is out of date, so don't try their examples.