fancy-dataclass

Spiff up your dataclasses with extra features.


Keywords
cli, config, dataclass, json, orm, serialize, toml
Install
pip install fancy-dataclass==0.3.1

Documentation

PyPI - Version GitHub Actions Workflow Status Coverage Status Read the Docs License: MIT pre-commit

Basics

🤵🏻‍♂️ Fancy Dataclass: A library to spiff up your dataclasses with extra features.

Introduction

Python 3.7 introduced the dataclasses module which lets you write "statically typed" classes using the type hinting mechanism.

By inspecting dataclasses' type annotations, it is possible to endow them with special powers that help cut down on boilerplate code in a wide variety of domains, such as:

  • JSON/TOML conversion: convert dataclasses to JSON/TOML files and vice versa
  • Configuration management: store global configurations and use them anywhere in your program
  • SQL persistence: define SQL tables, and save/load objects from a database
  • CLI parsing: parse command-line arguments and store their values in a dataclass, then use them to execute your main program logic
  • Subprocess calls: generate command-line arguments to be passed to another program

fancy_dataclass borrows ideas from other excellent libraries such as marshmallow, pydantic, and argparse_dataclass, while aiming to be as lightweight as possible in terms of its dependencies and learning curve.

How to install

pip install fancy-dataclass

Requires Python 3.8 or higher.

Example

Regular dataclass

@dataclass
class Person:
    name: str
    age: int
    height: float
    hobbies: list[str]

Fancy dataclass

@dataclass
class Person(JSONDataclass):
    name: str
    age: int
    height: float
    hobbies: list[str]

Usage:

>>> person = Person(
    name='John Doe',
    age=47,
    height=71.5,
    hobbies=['reading', 'juggling', 'cycling']
)

>>> print(person.to_json_string(indent=2))

{
  "name": "John Doe",
  "age": 47,
  "height": 71.5,
  "hobbies": [
    "reading",
    "juggling",
    "cycling"
  ]
}

Documentation

Read the official documentation here.

The documentation is made with Material for MkDocs and is hosted by Read the Docs.

View the Changelog here.

License

This library is distributed under the terms of the MIT license.