dataclass_wizard package

Subpackages

Submodules

dataclass_wizard.abstractions module

dataclass_wizard.bases module

dataclass_wizard.bases_meta module

dataclass_wizard.class_helper module

dataclass_wizard.constants module

dataclass_wizard.decorators module

dataclass_wizard.dumpers module

dataclass_wizard.enums module

class dataclass_wizard.enums.DateTimeTo(*values)[source]

Bases: Enum

ISO = 0
TIMESTAMP = 1
class dataclass_wizard.enums.EnvKeyStrategy(*values)[source]

Bases: Enum

Defines how environment variable names are resolved for dataclass fields.

This controls which keys are tried, and in what order, when loading values from environment variables, .env files, or Docker secrets.

Strategies:

  • ENV (default):

    Uses conventional environment variable naming. Tries SCREAMING_SNAKE_CASE first, then snake_case.

    Example:

    Field: my_field_name Keys tried: MY_FIELD_NAME, my_field_name

  • FIELD_FIRST:

    Tries the field name as written first, then environment-style variants.

    Example:

    Field: myFieldName Keys tried: myFieldName, MY_FIELD_NAME, my_field_name

    Useful when working with .env files or non-Python naming conventions.

  • STRICT:

    Uses explicit keys only. No automatic key derivation is performed (no prefixing, no casing transforms, no fallback lookups). Only __init__() kwargs and explicit aliases are considered.

    Useful when you want configuration loading to be fully deterministic.

ENV = 'env'
FIELD_FIRST = 'field'
STRICT = 'strict'
class dataclass_wizard.enums.EnvPrecedence(*values)[source]

Bases: Enum

ENV_ONLY = 'env-only'
SECRETS_DOTENV_ENV = 'secrets > dotenv > env'
SECRETS_ENV_DOTENV = 'secrets > env > dotenv'
class dataclass_wizard.enums.FuncWrapper(f)[source]

Bases: object

Wraps a callable f - which is occasionally useful, for example when defining functions as Enum values. See below answer for more details.

https://stackoverflow.com/a/40339397/10237506

Parameters:

f (Callable)

f
class dataclass_wizard.enums.KeyAction(*values)[source]

Bases: Enum

Specifies how to handle unknown keys encountered during deserialization.

Actions: - IGNORE: Skip unknown keys silently. - RAISE: Raise an exception upon encountering the first unknown key. - WARN: Log a warning for each unknown key.

For capturing unknown keys (e.g., including them in a dataclass), use the CatchAll field. More details: https://dcw.ritviknag.com/en/latest/common_use_cases/handling_unknown_json_keys.html#capturing-unknown-keys-with-catchall

IGNORE = 0
RAISE = 1
WARN = 2
class dataclass_wizard.enums.KeyCase(*values)[source]

Bases: Enum

Defines transformations for string keys, commonly used for mapping JSON keys to dataclass fields.

Key transformations:

  • CAMEL: Converts snake_case to camelCase. Example: my_field_name -> myFieldName

  • PASCAL: Converts snake_case to PascalCase (UpperCamelCase). Example: my_field_name -> MyFieldName

  • KEBAB: Converts camelCase or snake_case to kebab-case. Example: myFieldName -> my-field-name

  • SNAKE: Converts camelCase to snake_case. Example: myFieldName -> my_field_name

  • AUTO: Automatically maps JSON keys to dataclass fields by

    attempting all valid key casing transforms at runtime.

    Example: My-Field-Name -> my_field_name (cached for future lookups)

By default, no transformation is applied:
  • Example: MY_FIELD_NAME -> MY_FIELD_NAME

A = None
AUTO = None
C = <dataclass_wizard.enums.FuncWrapper object>
CAMEL = <dataclass_wizard.enums.FuncWrapper object>
K = <dataclass_wizard.enums.FuncWrapper object>
KEBAB = <dataclass_wizard.enums.FuncWrapper object>
P = <dataclass_wizard.enums.FuncWrapper object>
PASCAL = <dataclass_wizard.enums.FuncWrapper object>
S = <dataclass_wizard.enums.FuncWrapper object>
SNAKE = <dataclass_wizard.enums.FuncWrapper object>

dataclass_wizard.errors module

exception dataclass_wizard.errors.ExtraData(cls, extra_kwargs, field_names)[source]

Bases: JSONWizardError

Error raised when extra keyword arguments are passed in to the constructor or __init__() method of an EnvWizard subclass.

Note that this error class is raised by default, unless a value for the extra field is specified in the Meta class.

Parameters:
  • cls (type)

  • extra_kwargs (Collection[str])

  • field_names (Collection[str])

property message: str

Format and return an error message.

exception dataclass_wizard.errors.InvalidConditionError(cls, field_name)[source]

Bases: JSONWizardError

Error raised when a condition is not wrapped in SkipIf.

Parameters:
  • cls (type)

  • field_name (str)

property message: str

Format and return an error message.

exception dataclass_wizard.errors.JSONWizardError[source]

Bases: ABC, Exception

Base error class, for errors raised by this library.

property class_name: str | None
abstract property message: str

Format and return an error message.

static name(obj)[source]

Return the type or class name of an object

Return type:

str

property parent_cls: type | None
exception dataclass_wizard.errors.MissingData(nested_cls, **kwargs)[source]

Bases: ParseError

Error raised when unable to create a class instance, as the JSON object is None.

Parameters:

nested_cls (type)

property message: str

Format and return an error message.

exception dataclass_wizard.errors.MissingFields(base_err, obj, cls, cls_fields, cls_kwargs=None, missing_fields=None, missing_keys=None, **kwargs)[source]

Bases: JSONWizardError

Error raised when unable to create a class instance (most likely due to missing arguments)

Parameters:
  • base_err (Exception | None)

  • obj (JSONObject)

  • cls (type)

  • cls_fields (tuple[Field, ...])

  • cls_kwargs (JSONObject | None)

  • missing_fields (Collection[str] | None)

  • missing_keys (Collection[str] | None)

property message: str

Format and return an error message.

exception dataclass_wizard.errors.MissingVars(cls, missing_vars)[source]

Bases: JSONWizardError

Error raised when unable to create an instance of a EnvWizard subclass (most likely due to missing environment variables in the Environment)

Parameters:
  • cls (type)

  • missing_vars (Sequence[tuple[str, str | None, str, Any]])

property message: str

Format and return an error message.

exception dataclass_wizard.errors.ParseError(base_err, obj, ann_type, phase, _default_class=None, _field_name=None, _json_object=None, **kwargs)[source]

Bases: JSONWizardError

Base error when an error occurs during the JSON load process.

Parameters:
  • base_err (Exception)

  • obj (Any)

  • ann_type (type | Iterable | None)

  • phase (str)

  • _default_class (type | None)

  • _field_name (str | None)

  • _json_object (Any)

property field_name: str | None
property json_object
property message: str

Format and return an error message.

dataclass_wizard.errors.UnknownJSONKey

alias of UnknownKeysError

exception dataclass_wizard.errors.UnknownKeysError(unknown_keys, obj, cls, cls_fields, **kwargs)[source]

Bases: JSONWizardError

Error raised when unknown JSON key(s) are encountered in the JSON load process.

Note that this error class is only raised when the on_unknown_key=’RAISE’ flag is enabled in the Meta class.

Parameters:
  • unknown_keys (list[str] | str)

  • obj (JSONObject)

  • cls (type)

  • cls_fields (tuple[Field, ...])

property json_key
property message: str

Format and return an error message.

dataclass_wizard.errors.safe_dumps(o, **kwargs)[source]
Return type:

str

Parameters:
  • o (Any)

  • kwargs (Any)

dataclass_wizard.errors.show_deprecation_warning(fn, reason, fmt='Deprecated function {name} ({reason}).')[source]

Display a deprecation warning for a given function.

@param fn: Function which is deprecated. @param reason: Reason for the deprecation. @param fmt: Format string for the name/reason.

Return type:

None

Parameters:
  • fn (Callable | str)

  • reason (str)

  • fmt (str)

dataclass_wizard.errors.type_name(obj)[source]

Return the type or class name of an object

Return type:

str

Parameters:

obj (type)

dataclass_wizard.lazy_imports module

dataclass_wizard.loader_selection module

dataclass_wizard.loaders module

dataclass_wizard.log module

dataclass_wizard.models module

dataclass_wizard.models.Alias(*all, load=None, dump=None, env=None, skip=False, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>, doc=None)[source]

Maps one or more JSON key names to a dataclass field.

This function acts as an alias for dataclasses.field(...), with additional support for associating a field with one or more JSON keys. It customizes serialization and deserialization behavior, including handling keys with varying cases or alternative names.

The mapping is case-sensitive; JSON keys must match exactly (e.g., myField will not match myfield). If multiple keys are provided, the first one is used as the default for serialization.

Parameters:
  • all (str) – One or more JSON key names to associate with the dataclass field.

  • load (str | Sequence[str] | None) – Key(s) to use for deserialization. Defaults to all if not specified.

  • dump (str | None) – Key to use for serialization. Defaults to the first key in all.

  • skip (bool) – If True, the field is excluded during serialization. Defaults to False.

  • default (Any) – Default value for the field. Cannot be used with default_factory.

  • default_factory (Callable[[], Any]) – Callable to generate the default value. Cannot be used with default.

  • init (bool) – Whether the field is included in the generated __init__ method. Defaults to True.

  • repr (bool) – Whether the field appears in the __repr__ output. Defaults to True.

  • hash (bool) – Whether the field is included in the __hash__ method. Defaults to None.

  • compare (bool) – Whether the field is included in comparison methods. Defaults to True.

  • metadata (dict) – Additional metadata for the field. Defaults to None.

  • kw_only (bool) – If True, the field is keyword-only. Defaults to False.

Returns:

A dataclass field with additional mappings to one or more JSON keys.

Return type:

Field

Examples

Example 1 – Mapping multiple key names to a field:

from dataclasses import dataclass

from dataclass_wizard import Alias, LoadMeta, fromdict

@dataclass
class Example:
    my_field: str = Alias('key1', 'key2', default="default_value")

print(fromdict(Example, {'key2': 'a value!'}))
#> Example(my_field='a value!')

Example 2 – Skipping a field during serialization:

from dataclasses import dataclass

from dataclass_wizard import Alias, JSONWizard

@dataclass
class Example(JSONWizard):
    my_field: str = Alias('key', skip=True)

ex = Example.from_dict({'key': 'some value'})
print(ex)                  #> Example(my_field='a value!')
assert ex.to_dict() == {}  #> True
dataclass_wizard.models.AliasPath(*all, load=None, dump=None, skip=False, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>, doc=None)[source]

Creates a dataclass field mapped to one or more nested JSON paths.

This function acts as an alias for dataclasses.field(...), with additional functionality to associate a field with one or more nested JSON paths, including complex or deeply nested structures.

The mapping is case-sensitive, meaning that JSON keys must match exactly (e.g., “myField” will not match “myfield”). Nested paths can include dot notations or bracketed syntax for accessing specific indices or keys.

Parameters:
  • all (PathType | str) – One or more nested JSON paths to associate with the dataclass field (e.g., a.b.c or a["nested"]["key"]).

  • load (PathType | str | None) – Path(s) to use for deserialization. Defaults to all if not specified.

  • dump (PathType | str | None) – Path(s) to use for serialization. Defaults to all if not specified.

  • skip (bool) – If True, the field is excluded during serialization. Defaults to False.

  • default (Any) – Default value for the field. Cannot be used with default_factory.

  • default_factory (DefFactory[T] | Literal[_MISSING_TYPE.MISSING]) – A callable to generate the default value. Cannot be used with default.

  • init (bool) – Whether the field is included in the generated __init__ method. Defaults to True.

  • repr (bool) – Whether the field appears in the __repr__ output. Defaults to True.

  • hash (bool | None) – Whether the field is included in the __hash__ method. Defaults to None.

  • compare (bool) – Whether the field is included in comparison methods. Defaults to True.

  • metadata (Mapping[Any, Any] | None) – Additional metadata for the field. Defaults to None.

  • kw_only (bool) – If True, the field is keyword-only. Defaults to False.

Returns:

A dataclass field with additional mapping to one or more nested JSON paths.

Return type:

Field

Examples

Example 1 – Mapping multiple nested paths to a field:

from dataclasses import dataclass

from dataclass_wizard import AliasPath, fromdict

@dataclass
class Example:
    my_str: str = AliasPath('a.b.c.1', 'x.y["-1"].z', default="default_value")

# Maps nested paths ('a', 'b', 'c', 1) and ('x', 'y', '-1', 'z')
# to the `my_str` attribute. '-1' is treated as a literal string key,
# not an index, for the second path.

print(fromdict(Example, {'x': {'y': {'-1': {'z': 'some_value'}}}}))
#> Example(my_str='some_value')

Example 2 – Using Annotated:

from dataclasses import dataclass
from typing import Annotated

from dataclass_wizard import AliasPath, JSONWizard

@dataclass
class Example(JSONWizard):
    my_str: Annotated[str, AliasPath('my."7".nested.path.-321')]


ex = Example.from_dict({'my': {'7': {'nested': {'path': {-321: 'Test'}}}}})
print(ex)  #> Example(my_str='Test')
dataclass_wizard.models.Env(*load, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, **field_kwargs)[source]
class dataclass_wizard.models.Field(load_alias, dump_alias, env_vars, skip, path, default, default_factory, init, repr, hash, compare, metadata, kw_only, doc=None)[source]

Bases: Field

Alias to a dataclasses.Field, but one which also represents a mapping of one or more JSON key names to a dataclass field.

See the docs on the Alias() and AliasPath() for more info.

dump_alias
env_vars
load_alias
path
skip
dataclass_wizard.models.skip_if_field(condition, *, default=<dataclasses._MISSING_TYPE object>, default_factory=<dataclasses._MISSING_TYPE object>, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=<dataclasses._MISSING_TYPE object>, doc=None)[source]

dataclass_wizard.parsers module

dataclass_wizard.property_wizard module

dataclass_wizard.serial_json module

dataclass_wizard.type_def module

dataclass_wizard.wizard_mixins module

Module contents

Dataclass Wizard

Lightning-fast JSON wizardry for Python dataclasses — effortless serialization right out of the box!

Sample Usage:

>>> from dataclasses import dataclass, field
>>> from datetime import datetime
>>> from typing import Optional
>>>
>>> from dataclass_wizard import JSONWizard
>>> from dataclass_wizard.properties import property_wizard
>>>
>>>
>>> @dataclass
>>> class MyClass(JSONWizard, metaclass=property_wizard):
>>>
>>>     my_str: Optional[str]
>>>     list_of_int: list[int] = field(default_factory=list)
>>>     # You can also define this as `my_dt`, however only the annotation
>>>     # will carry over in that case, since the value is re-declared by
>>>     # the property below.
>>>     _my_dt: datetime = datetime(2000, 1, 1)
>>>
>>>     @property
>>>     def my_dt(self):
>>>     # A sample `getter` which returns the datetime with year set as 2010
>>>         if self._my_dt is not None:
>>>             return self._my_dt.replace(year=2010)
>>>         return self._my_dt
>>>
>>>     @my_dt.setter
>>>     def my_dt(self, new_dt: datetime):
>>>     # A sample `setter` which sets the inverse (roughly) of
>>>     # the `month` and `day`
>>>         self._my_dt = new_dt.replace(month=13 - new_dt.month,
>>>                                      day=30 - new_dt.day)
>>>
>>>
>>> string = '''{"myStr": 42, "listOFInt": [1, "2", 3]}'''
>>> c = MyClass.from_json(string)
>>> print(repr(c))
>>> # prints:
>>> #   MyClass(
>>> #       my_str='42',
>>> #       list_of_int=[1, 2, 3],
>>> #       my_dt=datetime.datetime(2010, 12, 29, 0, 0)
>>> #   )
>>> my_dict = {'My_Str': 'string', 'myDT': '2021-01-20T15:55:30Z'}
>>> c = MyClass.from_dict(my_dict)
>>> print(repr(c))
>>> # prints:
>>> #   MyClass(
>>> #       my_str='string',
>>> #       list_of_int=[],
>>> #       my_dt=datetime.datetime(2010, 12, 10, 15, 55, 30,
>>> #                               tzinfo=datetime.timezone.utc)
>>> #   )
>>> print(c.to_json())
>>> # prints:
>>> #   {"myStr": "string", "listOfInt": [], "myDt": "2010-12-10T15:55:30Z"}

For full documentation and more advanced usage, please see <https://dcw.ritviknag.com>.

copyright:
  1. 2021-2026 by Ritvik Nag.

license:

Apache 2.0, see LICENSE for more details.