Additional functionality for Python dataclasses
Project description
dataclass-extensions
Additional functionality for Python dataclasses
Installation
pip install dataclass-extensions
Features
Encode/decode to/from JSON-safe dictionaries
from dataclasses import dataclass
from dataclass_extensions import decode, encode
@dataclass
class Fruit:
calories: int
price: float
@dataclass
class FruitBasket:
fruit: Fruit
count: int
basket = FruitBasket(fruit=Fruit(calories=200, price=1.0), count=2)
assert encode(basket) == {"fruit": {"calories": 200, "price": 1.0}, "count": 2}
assert decode(FruitBasket, encode(basket)) == basket
Registrable subclasses
from dataclasses import dataclass
from dataclass_extensions import Registrable, decode, encode
@dataclass
class Fruit(Registrable):
calories: int
price: float
@Fruit.register("banana")
@dataclass
class Banana(Fruit):
calories: int = 200
price: float = 1.25
@Fruit.register("apple")
@dataclass
class Apple(Fruit):
calories: int = 150
price: float = 1.50
@dataclass
class FruitBasket:
fruit: Fruit
count: int
basket = FruitBasket(fruit=Apple(), count=2)
assert encode(basket) == {"fruit": {"calories": 150, "price": 1.5, "type": "apple"}, "count": 2}
assert decode(FruitBasket, encode(basket)) == basket
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
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dataclass_extensions-0.2.0.tar.gz.
File metadata
- Download URL: dataclass_extensions-0.2.0.tar.gz
- Upload date:
- Size: 15.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fa64d55d4a8712820a1da9ddfda60701c5acf8de6e5df477201a020c277ad2f5
|
|
| MD5 |
ac2f28bd5471b394022817961e348381
|
|
| BLAKE2b-256 |
f2b96959655a255813e28428aa5a072eda6024a14be88277ab8c5fbcc1df4e39
|
File details
Details for the file dataclass_extensions-0.2.0-py3-none-any.whl.
File metadata
- Download URL: dataclass_extensions-0.2.0-py3-none-any.whl
- Upload date:
- Size: 15.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
abdfccac4fb83494da07e17dfceaa73120974c0854d6c81a38c64b9ac63a5b4b
|
|
| MD5 |
bb4154260b5420c690b79c163304c588
|
|
| BLAKE2b-256 |
cb8d8a48dd9d9b8954752fa2d176816d257898cf379eacd8f5bf8c28d76b906e
|