dataclass_wizard package¶
Subpackages¶
- dataclass_wizard.utils package
- Submodules
- dataclass_wizard.utils.dataclass_compat module
- dataclass_wizard.utils.dict_helper module
- dataclass_wizard.utils.function_builder module
- dataclass_wizard.utils.json_util module
- dataclass_wizard.utils.lazy_loader module
- dataclass_wizard.utils.object_path module
- dataclass_wizard.utils.string_conv module
- dataclass_wizard.utils.type_conv module
- dataclass_wizard.utils.typing_compat module
- dataclass_wizard.utils.wrappers module
- Module contents
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.EnvKeyStrategy(*values)[source]¶
Bases:
EnumDefines 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_nameKeys tried:MY_FIELD_NAME,my_field_name
- FIELD_FIRST:
Tries the field name as written first, then environment-style variants.
- Example:
Field:
myFieldNameKeys 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:
objectWraps a callable f - which is occasionally useful, for example when defining functions as
Enumvalues. See below answer for more details.https://stackoverflow.com/a/40339397/10237506
- Parameters:
f (Callable)
- f¶
- class dataclass_wizard.enums.KeyAction(*values)[source]¶
Bases:
EnumSpecifies 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:
EnumDefines 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:
JSONWizardErrorError 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
Metaclass.- 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:
JSONWizardErrorError 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,ExceptionBase error class, for errors raised by this library.
- property class_name: str | None¶
- abstract property message: str¶
Format and return an error message.
- property parent_cls: type | None¶
- exception dataclass_wizard.errors.MissingData(nested_cls, **kwargs)[source]¶
Bases:
ParseErrorError 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:
JSONWizardErrorError 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:
JSONWizardErrorError 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:
JSONWizardErrorBase 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:
JSONWizardErrorError 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
Metaclass.- 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.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.,
myFieldwill not matchmyfield). 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
allif 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 toFalse.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 toTrue.repr (bool) – Whether the field appears in the
__repr__output. Defaults toTrue.hash (bool) – Whether the field is included in the
__hash__method. Defaults toNone.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 toFalse.
- Returns:
A dataclass field with additional mappings to one or more JSON keys.
- Return type:
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.cora["nested"]["key"]).load (PathType | str | None) – Path(s) to use for deserialization. Defaults to
allif not specified.dump (PathType | str | None) – Path(s) to use for serialization. Defaults to
allif 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:
FieldAlias 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()andAliasPath()for more info.- dump_alias¶
- env_vars¶
- load_alias¶
- path¶
- skip¶
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:
2021-2026 by Ritvik Nag.
- license:
Apache 2.0, see LICENSE for more details.