Skip to main content

Marshal dataclasses to/from JSON and Python dict objects, and add support for field properties with initial values.

Project description

https://img.shields.io/pypi/v/dataclass-wizard.svg https://img.shields.io/pypi/pyversions/dataclass-wizard.svg https://travis-ci.com/rnag/dataclass-wizard.svg?branch=main Documentation Status Updates

This library provides a set of simple, yet elegant wizarding tools for interacting with the Python dataclasses module.

Full documentation is at:

Features

Here are the supported features that dataclass-wizard currently provides:

  • JSON (de)serialization: marshal dataclasses to/from JSON and Python dict objects.

  • Field properties: support for using properties with default values in dataclass instances.

Usage

Using the built-in JSON marshalling support for dataclasses:

from dataclasses import dataclass, field
from typing import Optional, List, Tuple

from dataclass_wizard import JSONSerializable


@dataclass
class MyClass(JSONSerializable):
    my_str: Optional[str]
    is_active_tuple: Tuple[bool, ...]
    list_of_int: List[int] = field(default_factory=list)


string = """{"my_str": 20, "ListOfInt": ["1", "2", 3], "isActiveTuple": ["true", "false", 1, false]}"""
c = MyClass.from_json(string)
print(repr(c))
# prints:
#   MyClass(my_str='20', is_active_tuple=(True, False, True, False), list_of_int=[1, 2, 3])

print(c.to_json())
# prints:
#   {"myStr": "20", "isActiveTuple": [true, false, true, false], "listOfInt": [1, 2, 3]}

… and with the property_wizard, which provides supports for field properties with default values in dataclasses:

from dataclasses import dataclass, field
from typing import Union
from typing_extensions import Annotated

from dataclass_wizard import property_wizard


@dataclass
class Vehicle(metaclass=property_wizard):

    # Note: The example below uses the default value from the `field` extra in
    # the `Annotated` definition; if `wheels` were annotated as a `Union` type,
    # it would default to 0, because `int` appears as the first type argument.
    #
    # Any right-hand value assigned to `wheels` is ignored as it is simply
    # re-declared by the property; here it is simply omitted for brevity.
    wheels: Annotated[Union[int, str], field(default=4)]

    @property
    def wheels(self) -> int:
        return self._wheels

    @wheels.setter
    def wheels(self, wheels: Union[int, str]):
        self._wheels = int(wheels)


if __name__ == '__main__':
    v = Vehicle()
    print(v)
    # prints:
    #   Vehicle(wheels=4)

    v = Vehicle(wheels=3)
    print(v)
    # prints:
    #   Vehicle(wheels=3)

    v = Vehicle('6')
    print(v)
    # prints:
    #   Vehicle(wheels=6)

    assert v.wheels == 6, 'The constructor should use our setter method'

    # Confirm that we go through our setter method
    v.wheels = '123'
    assert v.wheels == 123

Installing Dataclass Wizard and Supported Versions

The Dataclass Wizard library is available on PyPI:

$ python -m pip install dataclass-wizard

The dataclass-wizard library officially supports Python 3.6 or higher.

JSON Marshalling

JSONSerializable is a Mixin class which provides the following helper methods that are useful for serializing (and loading) a dataclass instance to/from JSON, as defined by the AbstractJSONWizard interface.

Method

Example

Description

from_json

item = Product.from_json(string)

Converts a JSON string to an instance of the dataclass, or a list of the dataclass instances.

from_list

list_of_item = Product.from_list(l)

Converts a Python list object to a list of the dataclass instances.

from_dict

item = Product.from_dict(d)

Converts a Python dict object to an instance of the dataclass.

to_dict

d = item.to_dict()

Converts the dataclass instance to a Python dict object that is JSON serializable.

to_json

string = item.to_json()

Converts the dataclass instance to a JSON string representation.

Additionally, it adds a default __str__ method to subclasses, which will pretty print the JSON representation of an object; this is quite useful for debugging purposes. Whenever you invoke print(obj) or str(obj), for example, it’ll call this method which will format the dataclass object as a prettified JSON string. If you prefer a __str__ method to not be added, you can pass in str=False when extending from the Mixin class as mentioned here.

Note that the __repr__ method, which is implemented by the dataclass decorator, is also available. To invoke the Python object representation of the dataclass instance, you can instead use repr(obj) or f'{obj!r}'.

To mark a dataclass as being JSON serializable (and de-serializable), simply sub-class from JSONSerializable as shown below. You can also extend from the aliased name JSONWizard, if you prefer to use that instead.

Here is a (more) complete example of using the JSONSerializable Mixin class:

from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional, List, Union, Dict, Any, NamedTuple, DefaultDict
# Note: for Python 3.9+, you can import the following from `typing` instead
from typing_extensions import Literal

from dataclass_wizard import JSONSerializable


@dataclass
class MyTestClass(JSONSerializable):
    my_ledger: Dict[str, Any]
    the_answer_to_life: Optional[int]
    people: List['Person']
    is_enabled: bool = True


@dataclass
class Person:
    name: 'Name'
    age: int
    birthdate: datetime
    gender: Literal['M', 'F', 'N/A']
    occupation: Union[str, List[str]]
    hobbies: DefaultDict[str, List[str]] = field(
        default_factory=lambda: defaultdict(list))


class Name(NamedTuple):
    """A person's name"""
    first: str
    last: str
    salutation: Optional[Literal['Mr.', 'Mrs.', 'Ms.', 'Dr.']] = 'Mr.'


data = {
    'myLedger': {
        'Day 1': 'some details',
        'Day 17': ['a', 'sample', 'list']
    },
    'theAnswerTOLife': '42',
    'People': [
        {
            'name': ('Roberto', 'Fuirron'),
            'age': 21,
            'birthdate': '1950-02-28T17:35:20Z',
            'gender': 'M',
            'occupation': ['sailor', 'fisher'],
            'Hobbies': {'M-F': ('chess', 123, 'reading'), 'Sat-Sun': ['parasailing']}
        },
        {
            'name': ('Janice', 'Darr', 'Dr.'),
            'age': 45,
            'birthdate': '1971-11-05 05:10:59',
            'gender': 'F',
            'occupation': 'Dentist'
        }
    ]
}

c = MyTestClass.from_dict(data)

print(repr(c))
# prints the following result on a single line:
#   MyTestClass(
#       my_ledger={'Day 1': 'some details', 'Day 17': ['a', 'sample', 'list']},
#       the_answer_to_life=42,
#       people=[
#           Person(
#               name=Name(first='Roberto', last='Fuirron', salutation='Mr.'),
#               age=21, birthdate=datetime.datetime(1950, 2, 28, 17, 35, 20, tzinfo=datetime.timezone.utc),
#               gender='M', occupation=['sailor', 'fisher'],
#               hobbies=defaultdict(<class 'list'>, {'M-F': ['chess', '123', 'reading'], 'Sat-Sun': ['parasailing']})
#           ),
#           Person(
#               name=Name(first='Janice', last='Darr', salutation='Dr.'),
#               age=45, birthdate=datetime.datetime(1971, 11, 5, 5, 10, 59),
#               gender='F', occupation='Dentist',
#               hobbies=defaultdict(<class 'list'>, {})
#           )
#       ], is_enabled=True)

# calling `print` on the object invokes the `__str__` method, which will
# pretty-print the JSON representation of the object by default. You can
# also call the `to_json` method to print the JSON string on a single line.

print(c)
# prints:
#     {
#       "myLedger": {
#         "Day 1": "some details",
#         "Day 17": [
#           "a",
#           "sample",
#           "list"
#         ]
#       },
#       "theAnswerToLife": 42,
#       "people": [
#         {
#           "name": [
#             "Roberto",
#             "Fuirron",
#             "Mr."
#           ],
#           "age": 21,
#           "birthdate": "1950-02-28T17:35:20Z",
#           "gender": "M",
#           "occupation": [
#             "sailor",
#             "fisher"
#           ],
#           "hobbies": {
#             "M-F": [
#               "chess",
#               "123",
#               "reading"
#             ],
#             "Sat-Sun": [
#               "parasailing"
#             ]
#           }
#         },
#         {
#           "name": [
#             "Janice",
#             "Darr",
#             "Dr."
#           ],
#           "age": 45,
#           "birthdate": "1971-11-05T05:10:59",
#           "gender": "F",
#           "occupation": "Dentist",
#           "hobbies": {}
#         }
#       ],
#       "isEnabled": true
#     }

Field Properties

The Python dataclasses library has some key limitations with how it currently handles properties and default values.

The dataclass-wizard package natively provides support for using field properties with default values in dataclasses. The main use case here is to assign an initial value to the field property, if one is not explicitly passed in via the constructor method.

To use it, simply import the property_wizard helper function, and add it as a metaclass on any dataclass where you would benefit from using field properties with default values. The metaclass also pairs well with the JSONSerializable mixin class.

For more examples and important how-to’s on properties with default values, refer to the Using Field Properties section in the documentation.

Credits

This package was created with Cookiecutter and the rnag/cookiecutter-pypackage project template.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dataclass-wizard-0.5.1.tar.gz (68.2 kB view details)

Uploaded Source

Built Distribution

dataclass_wizard-0.5.1-py2.py3-none-any.whl (44.4 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file dataclass-wizard-0.5.1.tar.gz.

File metadata

  • Download URL: dataclass-wizard-0.5.1.tar.gz
  • Upload date:
  • Size: 68.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.0

File hashes

Hashes for dataclass-wizard-0.5.1.tar.gz
Algorithm Hash digest
SHA256 8bffb3dfe7bdbda829171d30fffb5f49db72f713d71372e9c308a86b67d3f4ae
MD5 45d5308c04bb1840ddf61e915ca28b00
BLAKE2b-256 f00ba13ea206c788b7335cc7f242e421ca58cbd0b4f73db82d9698decf7aa1ee

See more details on using hashes here.

File details

Details for the file dataclass_wizard-0.5.1-py2.py3-none-any.whl.

File metadata

  • Download URL: dataclass_wizard-0.5.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 44.4 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.6.3 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.9.0

File hashes

Hashes for dataclass_wizard-0.5.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 4e0dc50ea68c5f100c04df9b0e3ea950ab3c9e2c317736bb87de6082de2f01b3
MD5 d5969812e7b407bb4fc352dd468f6bc7
BLAKE2b-256 6ffebf34814658cf68848bc4731b957c05f2dd16d5eefae209901dfaa8f4adb0

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page