Skip to main content

No project description provided

Project description

Validates Python’s TypedDict

日本語の説明はこちら / Description in Japanese

About

This is a utility to validate a dict object using TypedDict. It recursively checks whether the dict has necessary keys and the values has appropriate type. It will be useful when you deserialize the json or yaml data, such as an API request or any file.

Currently supported types are generic types and Union (including Optional).

Requirements

  • Python 3.10 or higher

Installation

https://pypi.org/project/typeddict-validator/

pip install typeddict-validator

Usage

>>> from typing import TypedDict
>>> from typeddict_validator import validate_typeddict
>>>
>>> PersonDict = TypedDict("PersonDict", {"name": str, "age": int, "interests": list[str]})
>>>
>>> person = {"name": "Taro Yamada", "age": 30, "interests": ["programming", "painting"]}
>>>
>>> if validate_typeddict(person, PersonDict):
...     print("It's a PersonDict!")
It's a PersonDict!

By default, it will raise an error when the dict object does not match.

>>> robot = {"name": "Doraemon"}
>>>
>>> if validate_typeddict(robot, PersonDict):
...     print("It's a PersonDict!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/app/typeddict_validator/validate.py", line 37, in validate_typeddict
    raise DictMissingKeyException(key=k)
typeddict_validator.validate.DictMissingKeyException

You can use silent=True option not to raise an error.

>>> if not validate_typeddict(robot, PersonDict, silent=True):
...     print("It's not a PersonDict!!")
It's not a PersonDict!!

See typeddict_validator/validate_test.py for more examples.

Tests

docker run --mount source=$(pwd),target=/app,type=bind python:latest python3 -m unittest -v /app/typeddict_validator/validate_test.py

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

typeddict-validator-0.1.2.tar.gz (10.4 kB view hashes)

Uploaded Source

Built Distribution

typeddict_validator-0.1.2-py3-none-any.whl (6.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page