-
-
Notifications
You must be signed in to change notification settings - Fork 23
V1: Enhanced Union or | Type Parsing
Ritvik Nag edited this page Jan 17, 2025
·
5 revisions
Another benefit is augmented Union
or |
Type parsing, which now works as expected (related: #67, #163).
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal
from dataclass_wizard import JSONWizard
# set `debug=True` to see generated `from_dict` definition
@dataclass
class MyClass(JSONWizard, debug=False):
class _(JSONWizard.Meta):
# Enable opt-in to the "experimental" major release `v1` feature.
# This feature offers optimized performance for de/serialization.
# Defaults to False.
v1 = True
# Unsafe: Enables parsing of dataclasses in unions without requiring
# the presence of a `tag_key`, i.e., a dictionary key identifying the
# tag field in the input. Defaults to False.
v1_unsafe_parse_dataclass_in_union = True
literal_or_float: Literal['Auto'] | float
# Unions with primitives and dataclasses
entry: int | MoreDetails
@dataclass
class MoreDetails:
arg: str
# OK!
c = MyClass.from_dict({"literal_or_float": 1.23, "entry": 123})
print(repr(c)) #> MyClass(literal_or_float=1.23, entry=123)
# OK!
# Notes: `entry` specified as `str` -> deserialized as `int`
c = MyClass.from_dict({"literal_or_float": "1.23", "entry": "123"})
print(repr(c)) #> MyClass(literal_or_float=1.23, entry=123)
# OK!
c = MyClass.from_dict({"literal_or_float": "Auto", "entry": {"arg": "test"}})
print(repr(c)) #> MyClass(literal_or_float='Auto', entry=MoreDetails(arg='test'))