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, prefix='load', per_class_cache=False)[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.
prefix (str)
per_class_cache (bool)
- 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=None, prefix='load', per_class_cache=False)[source]¶
A helper decorator to handle generic types using setup_recursive_safe_function.
- Return type:
Callable- Parameters:
func (Callable)
per_class_cache (bool)
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.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.v1.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.v1.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.v1.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.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,BaseLoadHookThis 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
AbstractLoaderclass for documentation on any of the implemented methods.- classmethod load_dispatcher_for_annotation(tp, extras)[source]¶
Resolve the load dispatcher for a given annotation type.
Returns either a string reference to a dispatcher or a TypeInfo object, depending on how the annotation is handled.
base_cls is the original class object, useful when the annotated type is a
typing.ForwardRefobject.
- static load_fallback(tp, extras)[source]¶
Generate code for the fallback load handler when no specialized type matches.
The default fallback implementation is typically an identity / passthrough, but subclasses may override this behavior.
- 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)
intreturns: v–>vis anintor similarly annotated type.int(v)–>vis astrvalue of either a decimalinteger (e.g.
'123') or a non-fractional float value (e.g.42.0).
as_int(v)–>vis 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(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(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, **kwargs)[source]¶
- Parameters:
fields (tuple[Field, ...] | None)
- dataclass_wizard.v1.loaders.generate_field_code(cls_loader, extras, field, field_i, var_name=None)[source]¶
- 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, 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=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.,
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 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.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 (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')
- dataclass_wizard.v1.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.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, env_vars, skip, path, default, default_factory, init, repr, hash, compare, metadata, kw_only)[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¶
- class dataclass_wizard.v1.models.PatternBase(base, patterns=None, tz_info=None)[source]¶
Bases:
object- base¶
- patterns¶
- tz_info¶
- class dataclass_wizard.v1.models.TypeInfo(origin, args=None, name=None, i=1, field_i=1, prefix='v', val_name=None, index=None)[source]¶
Bases:
object- args¶
- field_i¶
- i¶
- property in_optional¶
- index¶
- name¶
- origin¶
- prefix¶
- v_for_def()[source]¶
Returns a safe value for function def statements (e.g., no dot (.) or indices [])
- val_name¶
- dataclass_wizard.v1.models.ensure_type_ref(extras, tp, *, name=None, prefix='', is_builtin=False)[source]¶
Return a safe symbol name for tp to use in generated code.
Adds entries to extras[‘locals’] only when required (non-builtins, non-collection literals, and cases where a stable local alias is needed).
- Return type:
str
Module contents¶
- dataclass_wizard.v1.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=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.,
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 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.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 (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.DumpMixin[source]¶
Bases:
AbstractDumperGenerator,BaseDumpHookThis Mixin class derives its name from the eponymous json.dumps function. Essentially it contains helper methods to convert a dataclass to JSON strings (or a Python dictionary object).
Refer to the
AbstractDumperclass for documentation on any of the implemented methods.- classmethod dump_dispatcher_for_annotation(tp, extras)[source]¶
Resolve the dump dispatcher for a given annotation type.
Returns either a string reference to a dispatcher or a TypeInfo object, depending on how the annotation is handled.
base_cls is the original class object, useful when the annotated type is a
typing.ForwardRefobject.
- static dump_fallback(tp, _extras)[source]¶
Generate code for the fallback dump handler when no specialized type matches.
The default fallback implementation is typically an identity / passthrough, but subclasses may override this behavior.
- static dump_from_bool(tp, _extras)¶
Generate code to dump a value from a boolean field.
- classmethod dump_from_bytearray(tp, extras)[source]¶
Generate code to dump a value from a bytearray field.
- static dump_from_dataclass(tp, extras)[source]¶
Generate code to dump a value from a dataclass type field.
- classmethod dump_from_datetime(tp, extras)[source]¶
Generate code to dump a value from a datetime field.
- classmethod dump_from_defaultdict(tp, extras)¶
Generate code to dump a value from a defaultdict field.
- classmethod dump_from_dict(tp, extras)[source]¶
Generate code to dump a value from a dictionary field.
- static dump_from_float(tp, _extras)¶
Generate code to dump a value from a float field.
- static dump_from_int(tp, _extras)¶
Generate code to dump a value from an integer field.
- classmethod dump_from_iterable(tp, extras)[source]¶
Generate code to dump a value from an iterable field (list, set, etc.).
- static dump_from_literal(tp, _extras)¶
Generate code to dump a literal.
- classmethod dump_from_named_tuple(tp, extras)[source]¶
Generate code to dump a value from a named tuple field.
- classmethod dump_from_named_tuple_untyped(tp, extras)[source]¶
Generate code to dump a value from an untyped named tuple.
- static dump_from_str(tp, _extras)¶
Generate code to dump a value from a string field.
- static dump_from_timedelta(tp, extras)[source]¶
Generate code to dump a value from a timedelta field.
- classmethod dump_from_typed_dict(tp, extras)[source]¶
Generate code to dump a value from a typed dictionary field.
- classmethod dump_from_union(cls, tp, extras)[source]¶
Generate code to dump a value from a Union[X, Y, …] (one of [X, Y, …] possible types)
- transform_dataclass_field = None¶
- dataclass_wizard.v1.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.v1.EnvWizard(**kwargs)[source]¶
Bases:
object- class Meta[source]¶
Bases:
BaseEnvWizardMetaInner meta class that can be extended by sub-classes for additional customization with the environment load process.
- raw_dict()[source]¶
Same as
__dict__, but only returns values for fields defined on the EnvWizard instance. See__field_names__for more info.Note
The values in the returned dictionary object are not needed to be JSON serializable. Use
to_dict()if this is required.- Return type:
JSONObject
- Parameters:
self (E_)
- classmethod register_type(*, load=None, dump=None, mode=None)¶
- Return type:
None
- to_dict(*, cls=None, dict_factory=<class 'dict'>, exclude=None, **kwargs)¶
Return the fields of a dataclass instance as a new dictionary mapping field names to field values.
Example usage:
@dataclass class C:
x: int y: int
c = C(1, 2) assert asdict(c) == {‘x’: 1, ‘y’: 2}
When directly invoking this function, an optional Meta configuration for the dataclass can be specified via
DumpMeta; by default, this will apply recursively to any nested dataclasses. Here’s a sample usage of this below:>>> DumpMeta(key_transform='CAMEL').bind_to(MyClass) >>> asdict(MyClass(my_str="value"))
If given, ‘dict_factory’ will be used instead of built-in dict. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts.
- Return type:
dict[str,Any]- Parameters:
o (T)
exclude (Collection[str] | None)
- class dataclass_wizard.v1.LoadMixin[source]¶
Bases:
AbstractLoaderGenerator,BaseLoadHookThis 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
AbstractLoaderclass for documentation on any of the implemented methods.- classmethod load_dispatcher_for_annotation(tp, extras)[source]¶
Resolve the load dispatcher for a given annotation type.
Returns either a string reference to a dispatcher or a TypeInfo object, depending on how the annotation is handled.
base_cls is the original class object, useful when the annotated type is a
typing.ForwardRefobject.
- static load_fallback(tp, extras)[source]¶
Generate code for the fallback load handler when no specialized type matches.
The default fallback implementation is typically an identity / passthrough, but subclasses may override this behavior.
- 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)
intreturns: v–>vis anintor similarly annotated type.int(v)–>vis astrvalue of either a decimalinteger (e.g.
'123') or a non-fractional float value (e.g.42.0).
as_int(v)–>vis 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(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(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¶