Structure unstructured data for the purpose of static type checking
Maintained. Last release 7 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity.
pip install typecatstypecats
Structure unstructured data for the purpose of static type
checking. An opinionated wrapper for attrs and cattrs.
In many web services it is common to consume or generate JSON or some
JSON-like representation of data. JSON translates quite nicely to core
Python objects such as dicts and lists. However, if your data is
structured, it is nice to be able to work with it in a structured
manner, i.e. with Python objects. Python objects give you better code
readability, and in more recent versions of Python they are also
capable of being statically type-checked with a tool like mypy.
attrs is an excellent library for defining boilerplate-free Python
classes that are easy to work with and that make static type-checking
with mypy a breeze. You define your attributes and their types with
a very clean syntax, attrs gives you constructors and dunder
methods, and mypy brings the static type-checking.
Throwing cattrs into the mix, you can have pleasant and simple
conversions to and from unstructured data with extremely low
boilerplate as well.
typecats, and its core decorator Cat, is a thin opinionated layer
on top of these two runtime libraries (attrs and cattrs) and the
develop-time mypy. It defines an attrs class with a few additional
features. The 4 core features are:
Features
-
Built-in
strucandunstruc.Static class function
strucand object methodunstrucadded to every class type defined as a Cat, which pass directly through to their underlyingstructureandunstructureimplementations incattrs.@Cat class TestCat: name: str age: int try: TestCat.struc(dict(name='Tom', age=9)) == TestCat(name='Tom', age=9) TestCat.struc(dict(name='Tom', age=9)).unstruc() == dict(name='Tom', age=9) except StructuringError as e: ...Rationale
Make your code easier to read, create a common pattern for defining, structuring, and unstructuring pure data objects, and require fewer imports - just import your defined type and go! Abbreviated forms of the verbs
structureandunstructurewere chosen to underscore the difference between the built-incattrsverbs and to reduce code clutter slightly for what is intended to be a common and idiomatic operation.