dataclass_wizard.utils package¶
Submodules¶
dataclass_wizard.utils.dataclass_compat module¶
Pulling some functions removed in recent versions of Python into the module for continued compatibility. All function names and bodies are left exactly as they were prior to being removed.
dataclass_wizard.utils.dict_helper module¶
Dict helper module
- class dataclass_wizard.utils.dict_helper.DictWithLowerStore(data=None, **kwargs)[source]¶
Bases:
dict
A
dict
-like object with a lower-cased key store.All keys are expected to be strings. The structure remembers the case of the lower-cased key to be set, and methods like
get()
andget_key()
will use the lower-cased store. However, querying and contains testing is case sensitive:dls = DictWithLowerStore() dls['Accept'] = 'application/json' dls['aCCEPT'] == 'application/json' # False (raises KeyError) dls['Accept'] == 'application/json' # True dls.get('aCCEPT') == 'application/json' # True dls.get_key('aCCEPT') == 'Accept' # True list(dls) == ['Accept'] # True
Note
I don’t want to use the CaseInsensitiveDict from request.structures, because it turns out the lookup via that dict implementation is rather slow. So this version is somewhat of a trade-off, where I retain the same speed on lookups as a plain dict, but I also have a lower-cased key store, in case I ever need to use it.
- class dataclass_wizard.utils.dict_helper.NestedDict[source]¶
Bases:
dict
A dictionary that automatically creates nested dictionaries for missing keys.
This class extends the built-in dict to simplify working with deeply nested structures. If a key is accessed but does not exist, it will be created automatically with a new NestedDict as its value.
Source: https://stackoverflow.com/a/5369984/10237506
- Example:
>>> nd = NestedDict() >>> nd['a']['b']['c'] = 42 >>> nd {'a': {'b': {'c': 42}}}
>>> nd['x']['y'] {}
dataclass_wizard.utils.function_builder module¶
- class dataclass_wizard.utils.function_builder.FunctionBuilder[source]¶
Bases:
object
- add_line(line)[source]¶
Add a line to the current function’s body with proper indentation.
- Parameters:
line (str)
- add_lines(*lines)[source]¶
Add lines to the current function’s body with proper indentation.
- Parameters:
lines (str)
- current_function¶
- elif_(condition)[source]¶
Equivalent to the elif statement in Python.
Sample Usage: :rtype:
FunctionBuilder
>>> with FunctionBuilder().elif_('something is True'): >>> ...
Will generate the following code:
>>> elif something is True: >>> ...
- Parameters:
condition (str)
- Return type:
- else_()[source]¶
Equivalent to the else statement in Python.
Sample Usage: :rtype:
FunctionBuilder
>>> with FunctionBuilder().else_(): >>> ...
Will generate the following code:
>>> else: >>> ...
- Return type:
- except_(cls, var_name=None, *custom_classes)[source]¶
Equivalent to the except block in Python.
Sample Usage:
>>> with FunctionBuilder().except_(TypeError, 'exc'): >>> ...
Will generate the following code:
>>> except TypeError as exc: >>> ...
- Parameters:
cls (type[Exception])
var_name (str | None)
custom_classes (type[Exception])
- except_multi(*classes)[source]¶
Equivalent to the except block in Python.
Sample Usage:
>>> with FunctionBuilder().except_multi(AttributeError, TypeError, ValueError): >>> ...
Will generate the following code:
>>> except (AttributeError, TypeError, ValueError): >>> ...
- Parameters:
classes (type[Exception])
- for_(condition)[source]¶
Equivalent to the for statement in Python.
Sample Usage: :rtype:
FunctionBuilder
>>> with FunctionBuilder().for_('i in range(3)'): >>> ...
Will generate the following code:
>>> for i in range(3): >>> ...
- Parameters:
condition (str)
- Return type:
- function(name, args, return_type=<dataclasses._MISSING_TYPE object>, locals=None)[source]¶
Start a new function definition with optional return type.
- Return type:
- Parameters:
name (str)
args (list)
- functions¶
- globals¶
- if_(condition, comment='')[source]¶
Equivalent to the if statement in Python.
Sample Usage: :rtype:
FunctionBuilder
>>> with FunctionBuilder().if_('something is True'): >>> ...
Will generate the following code:
>>> if something is True: >>> ...
- Parameters:
condition (str)
comment (str)
- Return type:
- indent_level¶
- namespace¶
- prev_function¶
- try_()[source]¶
Equivalent to the try block in Python.
Sample Usage: :rtype:
FunctionBuilder
>>> with FunctionBuilder().try_(): >>> ...
Will generate the following code:
>>> try: >>> ...
- Return type:
dataclass_wizard.utils.json_util module¶
JSON Helper Utilities - only internally used in errors.py
,
i.e. for rendering exceptions.
Note
This module should not be imported anywhere at the top-level of another library module!
dataclass_wizard.utils.lazy_loader module¶
Utility for lazy loading Python modules.
Credits: https://wil.yegelwel.com/lazily-importing-python-modules/
- class dataclass_wizard.utils.lazy_loader.LazyLoader(parent_module_globals, name, extra=None, local_name=None, warning=None)[source]¶
Bases:
ModuleType
Lazily import a module, mainly to avoid pulling in large dependencies. contrib, and ffmpeg are examples of modules that are large and not always needed, and this allows them to only be loaded when they are used.
dataclass_wizard.utils.object_path module¶
dataclass_wizard.utils.string_conv module¶
- dataclass_wizard.utils.string_conv.normalize(string)[source]¶
Normalize a string - typically a dataclass field name - for comparison purposes.
- Return type:
str
- Parameters:
string (str)
- dataclass_wizard.utils.string_conv.possible_json_keys(field)[source]¶
Maps a dataclass field name to its possible keys in a JSON object.
This function checks multiple naming conventions (e.g., camelCase, PascalCase, kebab-case, etc.) to find the matching key in the JSON object o. It also caches the mapping for future use.
- Return type:
list
[str
]- Parameters:
field (str)
- Args:
field (str): The dataclass field name to map.
- Returns:
list[str]: The possible JSON keys for the given field.
- dataclass_wizard.utils.string_conv.repl_or_with_union(s)[source]¶
Replace all occurrences of PEP 604- style annotations (i.e. like X | Y) with the Union type from the typing module, i.e. like Union[X, Y].
This is a recursive function that splits a complex annotation in order to traverse and parse it, i.e. one that is declared as follows:
dict[str | Optional[int], list[list[str] | tuple[int | bool] | None]]
- Parameters:
s (str)
- dataclass_wizard.utils.string_conv.to_camel_case(string)[source]¶
Convert a string to Camel Case.
Examples:
>>> to_camel_case("device_type") 'deviceType'
- Return type:
str
- Parameters:
string (str)
- dataclass_wizard.utils.string_conv.to_lisp_case(string)[source]¶
Make a hyphenated, lowercase form from the expression in the string.
Example:
>>> to_lisp_case("DeviceType") 'device-type'
- Return type:
str
- Parameters:
string (str)
dataclass_wizard.utils.type_conv module¶
- dataclass_wizard.utils.type_conv.as_bool(o)[source]¶
Return o if already a boolean, otherwise return the boolean value for o.
- Parameters:
o (str | bool | int | float)
- dataclass_wizard.utils.type_conv.as_date(o, base_type=<class 'datetime.date'>, default=None, raise_=True)[source]¶
Attempt to convert an object o to a
date
object using the below logic.str
: convert date strings (in ISO format) via the built-infromisoformat
method.Number
(int or float): Convert a numeric timestamp via thebuilt-in
fromtimestamp
method.
date
: Return object o if it’s already of this type orsub-type.
Otherwise, if we’re unable to convert the value of o to a
date
as expected, raise an error if the raise_ parameter is true; if not, return default instead.- Parameters:
o (str | Number | date)
- dataclass_wizard.utils.type_conv.as_date_v1(o, __from_timestamp)[source]¶
V1: Attempt to convert an object o to a
date
object using the below logic.Number
(int or float): Convert a numeric timestamp via thebuilt-in
fromtimestamp
method, and return a date.
base_type
: Return object o if it’s already of this type.
Note: It is assumed that o is not a
str
(in ISO format), as de-serialization inv1
already checks for this.Otherwise, if we’re unable to convert the value of o to a
date
as expected, raise an error.- Parameters:
o (int | float | date)
__from_timestamp (Callable[[float], date])
- dataclass_wizard.utils.type_conv.as_datetime(o, base_type=<class 'datetime.datetime'>, default=None, raise_=True)[source]¶
Attempt to convert an object o to a
datetime
object using the below logic.str
: convert datetime strings (in ISO format) via the built-infromisoformat
method.Number
(int or float): Convert a numeric timestamp via thebuilt-in
fromtimestamp
method, and return a UTC datetime.
datetime
: Return object o if it’s already of this type orsub-type.
Otherwise, if we’re unable to convert the value of o to a
datetime
as expected, raise an error if the raise_ parameter is true; if not, return default instead.- Parameters:
o (str | Number | datetime)
- dataclass_wizard.utils.type_conv.as_datetime_v1(o, __from_timestamp, __tz=None)[source]¶
V1: Attempt to convert an object o to a
datetime
object using the below logic.Number
(int or float): Convert a numeric timestamp via thebuilt-in
fromtimestamp
method, and return a UTC datetime.
base_type
: Return object o if it’s already of this type.
Note: It is assumed that o is not a
str
(in ISO format), as de-serialization inv1
already checks for this.Otherwise, if we’re unable to convert the value of o to a
datetime
as expected, raise an error.- Parameters:
o (int | float | datetime)
__from_timestamp (Callable[[float, tzinfo], datetime])
- dataclass_wizard.utils.type_conv.as_dict(o, kv_sep='=', sep=',')[source]¶
Return o if already a dict. If o is a string, split it on sep and then split each result by kv_sep, and return the dict result.
- Parameters:
o (str | Iterable)
- dataclass_wizard.utils.type_conv.as_enum(o, base_type, lookup_func=<function <lambda>>, transform_func=<function <lambda>>, raise_=True)[source]¶
Return o if it’s already an
Enum
of type base_type. If o is None or an empty string, return None.Otherwise, attempt to convert the object o to a
base_type
using the below logic: :rtype:Optional
[TypeVar
(E
, bound=Enum
)]If o is a string, we’ll put it through our transform_func before a lookup. The default one upper-cases the string and replaces spaces with underscores, since that’s typically how we define Enum names.
Then, convert to a
base_type
using the lookup_func. The one looks up by the Enumname
field.
- Raises:
ParseError – If the lookup for the Enum member fails, and the raise_ flag is enabled.
- Parameters:
o (AnyStr | int | float)
base_type (Type[E])
- Return type:
E | None
- dataclass_wizard.utils.type_conv.as_int(o, base_type=<class 'int'>, default=0, raise_=True)[source]¶
Return o if already a int, otherwise return the int value for a string. If o is None or an empty string, return default instead.
If o cannot be converted to an int, raise an error if raise_ is true, other return default instead.
- Raises:
TypeError – If o is a bool (which is an int sub-class)
ValueError – When o cannot be converted to an int, and the raise_ parameter is true
- Parameters:
o (str | int | float | bool | None)
- dataclass_wizard.utils.type_conv.as_int_v1(o, tp, base_type=<class 'int'>)[source]¶
Attempt to convert o to an int.
- This assumes the following checks already happen:
tp is base_type
tp is str and ‘.’ in o and float(o).is_integer()
tp is str and ‘.’ in o and not float(o).is_integer() –> IMPLIED
tp is str and ‘.’ not in o
If o cannot be converted to an int, raise an error.
- Raises:
TypeError – If o is a bool (which is an int subclass)
ValueError – When o cannot be converted to an int
- Parameters:
o (float | bool)
tp (type)
- dataclass_wizard.utils.type_conv.as_list(o, sep=',')[source]¶
Return o if already a list. If o is a string, split it on sep and return the list result.
- Parameters:
o (str | Iterable)
- dataclass_wizard.utils.type_conv.as_str(o, base_type=<class 'str'>)[source]¶
Return o if already a str, otherwise return the string value for o. If o is None, return an empty string instead.
- Parameters:
o (str | None)
- dataclass_wizard.utils.type_conv.as_time(o, base_type=<class 'datetime.time'>, default=None, raise_=True)[source]¶
Attempt to convert an object o to a
time
object using the below logic.str
: convert time strings (in ISO format) via the built-infromisoformat
method.time
: Return object o if it’s already of this type orsub-type.
Otherwise, if we’re unable to convert the value of o to a
time
as expected, raise an error if the raise_ parameter is true; if not, return default instead.- Parameters:
o (str | time)
- dataclass_wizard.utils.type_conv.as_time_v1(o, base_type)[source]¶
V1: Attempt to convert an object o to a
time
object using the below logic.base_type
: Return object o if it’s already of this type.
Note: It is assumed that o is not a
str
(in ISO format), as de-serialization inv1
already checks for this.Otherwise, if we’re unable to convert the value of o to a
time
as expected, raise an error.- Parameters:
o (time | Any)
base_type (type[time])
- dataclass_wizard.utils.type_conv.as_timedelta(o, base_type=<class 'datetime.timedelta'>, default=None, raise_=True)[source]¶
Attempt to convert an object o to a
timedelta
object using the below logic.str
: If the string is in a numeric form like “1.23”, we convert it to afloat
and assume it’s in seconds. Otherwise, we convert strings via thepytimeparse.parse
function.int
orfloat
: A numeric value is assumed to be in seconds. In this case, it is passed in to the constructor liketimedelta(seconds=...)
timedelta
: Return object o if it’s already of this type orsub-type.
Otherwise, if we’re unable to convert the value of o to a
timedelta
as expected, raise an error if the raise_ parameter is true; if not, return default instead.- Parameters:
o (str | int | float | timedelta)
- dataclass_wizard.utils.type_conv.date_to_timestamp(d)[source]¶
Retrieves the epoch timestamp of a
date
object, as an inthttps://stackoverflow.com/a/15661036/10237506
- Return type:
int
- Parameters:
d (date)
dataclass_wizard.utils.typing_compat module¶
Utility module for checking generic types provided by the typing library.
- dataclass_wizard.utils.typing_compat.eval_forward_ref(base_type, cls)[source]¶
Evaluate a forward reference using the class globals, and return the underlying type reference.
- Parameters:
base_type (FREF)
cls (type)
- dataclass_wizard.utils.typing_compat.eval_forward_ref_if_needed(base_type, base_cls)[source]¶
If needed, evaluate a forward reference using the class globals, and return the underlying type reference.
- Parameters:
base_type (type | FREF)
base_cls (type)
- dataclass_wizard.utils.typing_compat.get_args(tp)[source]¶
Get type arguments with all substitutions performed.
For unions, basic simplifications used by Union constructor are performed. Examples:
get_args(Dict[str, int]) == (str, int) get_args(int) == () get_args(Union[int, Union[T, int], str][int]) == (int, str) get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) get_args(Callable[[], T][int]) == ([], int)
- dataclass_wizard.utils.typing_compat.get_keys_for_typed_dict(cls)[source]¶
Given a
TypedDict
sub-class, returns a pair of (required_keys, optional_keys)
- dataclass_wizard.utils.typing_compat.get_origin(cls, raise_=False)¶
Get the un-subscripted value of a type. If we’re unable to retrieve this value, return type cls if raise_ is false.
This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar. Return None for unsupported types.
Examples:
get_origin(Literal[42]) is Literal get_origin(int) is int get_origin(ClassVar[int]) is ClassVar get_origin(Generic) is Generic get_origin(Generic[T]) is Generic get_origin(Union[T, int]) is Union get_origin(List[Tuple[T, T]][int]) == list
- Raises:
AttributeError – When the raise_ flag is enabled, and we are unable to retrieve the un-subscripted value.
- dataclass_wizard.utils.typing_compat.is_annotated(cls)¶
Detects a
typing.Annotated
class.
- dataclass_wizard.utils.typing_compat.is_generic(cls)[source]¶
Detects any kind of generic, for example List or List[int]. This includes “special” types like Union, Any ,and Tuple - anything that’s subscriptable, basically.
dataclass_wizard.utils.wrappers module¶
Wrapper utilities
- class dataclass_wizard.utils.wrappers.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¶