dataclass_wizard.v1 package¶
Submodules¶
dataclass_wizard.v1.decorators module¶
- dataclass_wizard.v1.decorators.process_patterned_date_time(func)[source]¶
Decorator for processing patterned date and time data.
If the ‘pattern’ key exists in the extras dictionary, it updates the base and origin of the type information and processes the pattern before calling the original function.
Supports both class methods and static methods.
- Return type:
Callable
- Parameters:
func (Callable)
- Args:
func (Callable): The function to decorate, either a class method or static method.
- Returns:
Callable: The wrapped function with pattern processing applied.
- dataclass_wizard.v1.decorators.setup_recursive_safe_function(func=None, *, fn_name=None, is_generic=False, add_cls=True)[source]¶
A decorator to ensure recursion safety and facilitate dynamic function generation with FunctionBuilder, supporting both generic and non-generic types.
The decorated function can define the logic for dynamically generated functions. If fn_name is provided, the decorator assumes that the function generation context (e.g., with fn_gen.function(…)) has already been handled externally and will not apply it again.
- Parameters:
func (Callable, optional) – The function to decorate. If None, the decorator is applied with arguments.
fn_name (str, optional) – A format string for dynamically generating function names, or None.
is_generic (bool, optional) – Whether the function deals with generic types.
add_cls (bool, optional) – Whether the class should be added to the function locals for FunctionBuilder.
- Returns:
The decorated function with recursion safety and dynamic function generation.
- Return type:
Callable
- dataclass_wizard.v1.decorators.setup_recursive_safe_function_for_generic(func)[source]¶
A helper decorator to handle generic types using setup_recursive_safe_function.
- Return type:
Callable
- Parameters:
func (Callable)
Parameters¶
- funcCallable
The function to be decorated, responsible for returning the generated function name.
Returns¶
- Callable
A wrapped function ensuring recursion safety for generic types.
dataclass_wizard.v1.enums module¶
- class dataclass_wizard.v1.enums.KeyAction(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[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://dataclass-wizard.readthedocs.io/en/latest/common_use_cases/handling_unknown_json_keys.html#capturing-unknown-keys-with-catchall
- IGNORE = 0¶
- RAISE = 1¶
- WARN = 2¶
- class dataclass_wizard.v1.enums.KeyCase(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[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.utils.wrappers.FuncWrapper object>¶
- CAMEL = <dataclass_wizard.utils.wrappers.FuncWrapper object>¶
- K = <dataclass_wizard.utils.wrappers.FuncWrapper object>¶
- KEBAB = <dataclass_wizard.utils.wrappers.FuncWrapper object>¶
- P = <dataclass_wizard.utils.wrappers.FuncWrapper object>¶
- PASCAL = <dataclass_wizard.utils.wrappers.FuncWrapper object>¶
- S = <dataclass_wizard.utils.wrappers.FuncWrapper object>¶
- SNAKE = <dataclass_wizard.utils.wrappers.FuncWrapper object>¶
dataclass_wizard.v1.loaders module¶
- class dataclass_wizard.v1.loaders.LoadMixin[source]¶
Bases:
AbstractLoaderGenerator
,BaseLoadHook
This Mixin class derives its name from the eponymous json.loads function. Essentially it contains helper methods to convert JSON strings (or a Python dictionary object) to a dataclass which can often contain complex types such as lists, dicts, or even other dataclasses nested within it.
Refer to the
AbstractLoader
class for documentation on any of the implemented methods.- static default_load_to(tp, extras)[source]¶
Generate code for the default load function if no other types match. Generally, this will be a stub load method.
- classmethod get_string_for_annotation(tp, extras)[source]¶
Generate code to get the parser (dispatcher) for a given annotation type.
base_cls is the original class object, useful when the annotated type is a
typing.ForwardRef
object.
- static load_to_bool(tp, extras)[source]¶
Generate code to load a value into a boolean field. Adds a helper function as_bool to the local context.
- classmethod load_to_bytearray(tp, extras)[source]¶
Generate code to load a value into a bytearray field.
- static load_to_dataclass(tp, extras)[source]¶
Generate code to load a value into a dataclass type field.
- classmethod load_to_datetime(cls, tp, extras)[source]¶
Generate code to load a value into a datetime field.
- classmethod load_to_defaultdict(tp, extras)[source]¶
Generate code to load a value into a defaultdict field.
- classmethod load_to_dict(tp, extras)[source]¶
Generate code to load a value into a dictionary field.
- static load_to_int(tp, extras)[source]¶
Generate code to load a value into an integer field.
- Current logic to parse (an annotated)
int
returns: v
–>v
is anint
or similarly annotated type.int(v)
–>v
is astr
value of either a decimalinteger (e.g.
'123'
) or a non-fractional float value (e.g.42.0
).
as_int(v)
–>v
is a non-fractionalfloat
, or in caseof “less common” types / scenarios. Note that empty strings and
None
(e.g. null values) are not supported.
- Current logic to parse (an annotated)
- classmethod load_to_iterable(tp, extras)[source]¶
Generate code to load a value into an iterable field (list, set, etc.).
- static load_to_literal(tp, extras)[source]¶
Generate code to confirm a value is equivalent to one of the provided literals.
- classmethod load_to_named_tuple(cls, tp, extras)[source]¶
Generate code to load a value into a named tuple field.
- classmethod load_to_named_tuple_untyped(tp, extras)[source]¶
Generate code to load a value into an untyped named tuple.
- classmethod load_to_typed_dict(cls, tp, extras)[source]¶
Generate code to load a value into a typed dictionary field.
- classmethod load_to_union(cls, tp, extras)[source]¶
Generate code to load a value into a Union[X, Y, …] (one of [X, Y, …] possible types)
- transform_json_field = None¶
- dataclass_wizard.v1.loaders.check_and_raise_missing_fields(_locals, o, cls, fields)[source]¶
- Parameters:
fields (tuple[Field, ...] | None)
- dataclass_wizard.v1.loaders.load_func_for_dataclass(cls, extras=None, loader_cls=<class 'dataclass_wizard.v1.loaders.LoadMixin'>, base_meta_cls=<class 'dataclass_wizard.bases.AbstractMeta'>)[source]¶
- Return type:
Optional
[Callable
[[dict
[str
,Any
]],TypeVar
(T
)]]- Parameters:
cls (type)
extras (Extras | None)
base_meta_cls (type)
dataclass_wizard.v1.models module¶
- dataclass_wizard.v1.models.Alias(*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=False)[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 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
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 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 LoadMeta, fromdict from dataclass_wizard.v1 import Alias @dataclass class Example: my_field: str = Alias('key1', 'key2', default="default_value") LoadMeta(v1=True).bind_to(Example) 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 JSONPyWizard from dataclass_wizard.v1 import Alias @dataclass class Example(JSONPyWizard): class _(JSONPyWizard.Meta): v1 = True 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.v1.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=False)[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
ora["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 (Callable[[], Any]) – 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) – 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 mapping to one or more nested JSON paths.
- Return type:
Examples
Example 1 – Mapping multiple nested paths to a field:
from dataclasses import dataclass from dataclass_wizard import fromdict, LoadMeta from dataclass_wizard.v1 import AliasPath @dataclass class Example: my_str: str = AliasPath('a.b.c.1', 'x.y["-1"].z', default="default_value") LoadMeta(v1=True).bind_to(Example) # 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 JSONPyWizard from dataclass_wizard.v1 import AliasPath @dataclass class Example(JSONPyWizard): class _(JSONPyWizard.Meta): v1 = True 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')
- class dataclass_wizard.v1.models.Extras[source]¶
Bases:
TypedDict
“Extra” config that can be used in the load / dump process.
-
cls:
type
¶
-
cls_name:
str
¶
-
config:
Type
[TypeVar
(META_
, bound= AbstractMeta)]¶
-
fn_gen:
FunctionBuilder
¶
-
locals:
dict
[str
,Any
]¶
-
pattern:
NotRequired
[PatternBase
]¶
-
recursion_guard:
dict
[type
,str
]¶
-
cls:
- class dataclass_wizard.v1.models.Field(load_alias, dump_alias, skip, path, default, default_factory, init, repr, hash, compare, metadata, kw_only)[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()
andAliasPath()
for more info.- dump_alias¶
- load_alias¶
- path¶
- skip¶
- class dataclass_wizard.v1.models.PatternBase(base, patterns=None, tz_info=None)[source]¶
Bases:
object
- base¶
- patterns¶
- tz_info¶
Module contents¶
- dataclass_wizard.v1.Alias(*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=False)[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 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
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 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 LoadMeta, fromdict from dataclass_wizard.v1 import Alias @dataclass class Example: my_field: str = Alias('key1', 'key2', default="default_value") LoadMeta(v1=True).bind_to(Example) 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 JSONPyWizard from dataclass_wizard.v1 import Alias @dataclass class Example(JSONPyWizard): class _(JSONPyWizard.Meta): v1 = True 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.v1.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=False)[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
ora["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 (Callable[[], Any]) – 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) – 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 mapping to one or more nested JSON paths.
- Return type:
Examples
Example 1 – Mapping multiple nested paths to a field:
from dataclasses import dataclass from dataclass_wizard import fromdict, LoadMeta from dataclass_wizard.v1 import AliasPath @dataclass class Example: my_str: str = AliasPath('a.b.c.1', 'x.y["-1"].z', default="default_value") LoadMeta(v1=True).bind_to(Example) # 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 JSONPyWizard from dataclass_wizard.v1 import AliasPath @dataclass class Example(JSONPyWizard): class _(JSONPyWizard.Meta): v1 = True 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')