Utilities to help with type checking.
Project description
This is a Python library of TypeGuard functions that can be used for static type narrowing, and runtime type checking.
is_json(
{
"str_key": "str_val",
"int_key": 1,
"float_key": 1.0,
"bool_key": True,
"none_key": None,
"list_key": [1, 2, "3", {"foo": "bar"}],
"dict_key": {"foo": "bar"},
},
) # True
Installation
pip install typeguards
Usage
Assert that an object is valid JSON.
from typeguards.json import is_json
assert is_json(
{
"str_key": "str_val",
"int_key": 1,
"float_key": 1.0,
"bool_key": True,
"none_key": None,
"list_key": [1, 2, "3", {"foo": "bar"}],
"dict_key": { # dict values can be nested infinitely
"foo": "bar",
},
},
) # OK
assert is_json("a string") # AssertionError
assert is_json([1, 2, 3]) # AssertionError
Assert that an object conforms to a JSON schema.
from typing import List, NamedTuple, TypedDict
from typeguards.json import is_json_schema
class HobbySchema(NamedTuple):
name: str
is_fun: bool
class UserSchema(TypedDict):
id: int
username: str
hobbies: List[HobbySchema] # Nested schema
assert is_json_schema(
{
"id": 7,
"username": "charlotte",
"hobbies": [{"name": "Hyrule Warriors: Age of Calamity", "is_fun": True}],
},
UserSchema,
) # OK
assert is_json_schema(
{
# No id, but still conforms to schema
"username": "oscar",
"hobbies": [{"name": "Whacking things", "is_fun": True}],
},
UserSchema,
) # OK
assert is_json_schema(
{
"bad-id": 123, # Doesn't conform to schema
"username": "narvin",
"hobbies": [{"name": "Watching coding videos", "is_fun": False}],
},
UserSchema,
) # AssertionError
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
typeguards-0.2.0.tar.gz
(7.3 kB
view hashes)
Built Distribution
Close
Hashes for typeguards-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 60e4d531c309cbe0029e982c524748888f2ad1c73f06a20dd0966e7721d41788 |
|
MD5 | 8e55f40ec7890e6e8ed93a2c4f94d50d |
|
BLAKE2b-256 | e935934b7fd1182fb0ce074d39bb23b8ece6b8bccbcb29b8db6a139bb3beb44c |