项目作者: crtomirmajer

项目描述 :
Easy Python dataclass marshalling/serialization with support for nested structures
高级语言: Python
项目地址: git://github.com/crtomirmajer/dataclass-marshal.git
创建时间: 2018-12-01T23:04:41Z
项目社区:https://github.com/crtomirmajer/dataclass-marshal

开源协议:GNU General Public License v3.0

下载


dataclass-marshal

Python package for marshalling (serializing) instances of classes decorated with @dataclass.

Supported serialization types

  • Simple types: bool, int, float, complex, str, bytes, bytearray
  • Container types: Tuple, List, Set, Dict
  • Other types: Decimal, datetime, UUID

Usage

  1. from typing import Any, Dict
  2. from dataclass_marshal import dataclass, marshal, unmarshal
  3. @dataclass
  4. class Product:
  5. id: int
  6. attributes: Dict[str, Any]
  7. product = Product(1, {'weight': 10})
  8. marshalled = marshal(product)
  9. # {'id': 1, 'attributes': {'weight': 10}}
  10. unmarshalled = unmarshal(marshalled, Product)
  11. # Product(id=1, attributes={'weight': 10})

Support for custom (un)marshallers

For custom types and non-@dataclass definitions it’s possible to register custom marshaller/unmarshaller.

  1. from dataclass_marshal import register, marshal
  2. class Dimensions:
  3. def __init__(self, height, width, depth):
  4. self.height = height
  5. self.width = width
  6. self.depth = depth
  7. register(Dimensions, marshaller=lambda x: x.__dict__, unmarshaller=lambda x: Dimensions(**x))
  8. marshalled = marshal(Dimensions(1,2,4))
  9. # {'height': 1, 'width': 2, 'depth': 4}