Make your dataclasses automatically validate their types
Project description
typed_json_dataclass
typed_json_dataclass
is a library that augments the Python3.7
dataclass feature in two
major ways:
- Add a way to recursively grab class dictionary definitions, thus making your dataclass JSON serializable
- Add a light amount of type validation to your dataclasses, so that you can validate that the JSON you're being given matches the data types that you're expecting.
By expressing your data as dataclasses, and by having your incoming data validated as it is received, you can easily implement the Data Transfer Object (DTO) pattern in your Python code.
This library can be thought of as a combination of attrs, cattrs, and marshamllow
Getting Started
Install the library from PyPI:
pip install typed_json_dataclass
Use the dataclass decorator just like normal, but add the TypedJsonMixin
from
this library, to your class definition. This will add 4 new methods to all of your dataclasses:
- from_dict()
@classmethod
def from_dict(cls, raw_dict):
"""Given a python dict, create an instance of the implementing class.
:raw_dict: A dictionary that represents the DTO to create
:returns: Returns an instance of the DTO, instantiated via the dict
"""
- from_json()
@classmethod
def from_json(cls, raw_json):
"""Given a raw json string, create an instance of the implementing class.
:raw_json: A json string that represents the DTO to create
:returns: Returns an instance of the DTO, instantiated via the json
"""
- to_dict()
def to_dict(self, *, keep_none=False):
"""Express the DTO as a dictionary.
:returns: Returns the instantiated DTO as a dictionary
"""
- to_json()
def to_json(self, *, keep_none=False):
"""Express the DTO as a json string.
:returns: Returns the instantiated DTO as a json string
"""
Examples
Converting your dataclass to a JSON serializable format:
from typing import List
from dataclasses import dataclass
from typed_json_dataclass import TypedJsonMixin
@dataclass
class Person(TypedJsonMixin):
name: str
age: int
@dataclass
class Family(TypedJsonMixin):
people: List[Person]
bob = Person(name='Bob', age=24)
alice = Person(name='Alice', age=32)
family = Family(people=[bob, alice])
print(family.to_json())
# => {"people": [{"name": "Bob", "age": 24}, {"name": "Alice", "age": 32}]}
If your data doesn't match the type definitions, you'll get a helpful error:
from dataclasses import dataclass
from typed_json_dataclass import TypedJsonMixin
@dataclass
class Person(TypedJsonMixin):
name: str
age: int
request_data = '{"name":"Bob","age":"24"}'
bob = Person.from_json(request_data)
# => TypeError: Person.age is expected to be <class 'int'>, but value 24 with type <class 'str'> was found instead
And you can parse data from a Python dict
as well. Just use the .from_dict()
function instead:
from dataclasses import dataclass
from typed_json_dataclass import TypedJsonMixin
@dataclass
class Person(TypedJsonMixin):
name: str
age: int
request_data_as_dict = {
'name': 'Alice',
'age': '32'
}
alice = Person.from_dict(request_data_as_dict)
# => TypeError: Person.age is expected to be <class 'int'>, but value 32 with type <class 'str'> was found instead
Changelog
0.1.1 - Sun, 2018-12-30
- Correct some lazy tests
0.1.0 - Sun, 2018-12-30
- We now support recursive ForwardRef type definitions
0.0.2 - Sun, 2018-12-30
- Added several open source project badges.
- Added much more useful information to the README.
- No code/functionality changes.
0.0.1 - Sun, 2018-12-30
- Created the base project and uploaded it to PyPI. Not much additional work has been done.
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
Built Distribution
Hashes for typed_json_dataclass-0.1.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7f68361f97b9a8b2c39798e82afb62904414f02e89c09c3b472894c8c8a130a3 |
|
MD5 | abe5504076c57c0b7522a82fbd757b2a |
|
BLAKE2b-256 | 8b7239ab790aab92173ddedd429303ad4be56cc938799f934a8dfbfa4b13add2 |
Hashes for typed_json_dataclass-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 577b44c3d680e468f533ecdd4f6474951c1af7a2fbb30985efa429e84e588ac3 |
|
MD5 | fd1c8db337afead4b98b49b73268a1df |
|
BLAKE2b-256 | 9cb28d683d276b7f490406c9e6f04c0e91081f75e316d274c5b5b1b2ec383ff4 |