dataclass_wizard.utils package

Submodules

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() and get_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.

copy() a shallow copy of D[source]
get(key)[source]

Do a case-insensitive lookup. This lower-cases key and looks up from the lower-cased key store.

get_key(key) str[source]

Return the original cased key

lower_items()[source]

Like iteritems(), but with all lowercase keys.

update([E, ]**F) None.  Update D from dict/iterable E and F.[source]

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

dataclass_wizard.utils.string_conv module

dataclass_wizard.utils.string_conv.normalize(string: str) str[source]

Normalize a string - typically a dataclass field name - for comparison purposes.

dataclass_wizard.utils.string_conv.repl_or_with_union(s: str)[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]]

dataclass_wizard.utils.string_conv.to_camel_case(string: str) str[source]

Convert a string to Camel Case.

Examples:

>>> to_camel_case("device_type")
'deviceType'
dataclass_wizard.utils.string_conv.to_lisp_case(string: str) str[source]

Make a hyphenated, lowercase form from the expression in the string.

Example:

>>> to_lisp_case("DeviceType")
'device-type'
dataclass_wizard.utils.string_conv.to_pascal_case(string)[source]

Converts a string to Pascal Case (also known as “Upper Camel Case”)

Examples:

>>> to_pascal_case("device_type")
'DeviceType'
dataclass_wizard.utils.string_conv.to_snake_case(string: str) str[source]

Make an underscored, lowercase form from the expression in the string.

Example:

>>> to_snake_case("DeviceType")
'device_type'

dataclass_wizard.utils.type_check module

dataclass_wizard.utils.type_conv module

dataclass_wizard.utils.type_conv.as_bool(o: Union[str, bool, dataclass_wizard.type_def.N])[source]

Return o if already a boolean, otherwise return the boolean value for o.

dataclass_wizard.utils.type_conv.as_date(o: typing.Union[str, numbers.Number, datetime.date], 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-in fromisoformat method.

  • Number (int or float): Convert a numeric timestamp via the

    built-in fromtimestamp method.

  • date: Return object o if it’s already of this type or

    sub-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.

dataclass_wizard.utils.type_conv.as_datetime(o: typing.Union[str, numbers.Number, datetime.datetime], 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-in fromisoformat method.

  • Number (int or float): Convert a numeric timestamp via the

    built-in fromtimestamp method.

  • datetime: Return object o if it’s already of this type or

    sub-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.

dataclass_wizard.utils.type_conv.as_enum(o: typing.Union[typing.AnyStr, dataclass_wizard.type_def.N], base_type: typing.Type[dataclass_wizard.type_def.E], lookup_func=<function <lambda>>, transform_func=<function <lambda>>, raise_=True) Optional[dataclass_wizard.type_def.E][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 :type:`base_type` using the below logic:

  • 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 :type:`base_type` using the lookup_func. The one looks up by the Enum name field.

Raises

ParseError – If the lookup for the Enum member fails, and the raise_ flag is enabled.

dataclass_wizard.utils.type_conv.as_int(o: typing.Optional[typing.Union[str, int, float, bool]], 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

dataclass_wizard.utils.type_conv.as_list(o: Union[str, List[str]], sep=',')[source]

Return o if already a list. If o is None or an empty string, return an empty list. Otherwise, split the string on sep and return the list result.

dataclass_wizard.utils.type_conv.as_str(o: typing.Optional[str], base_type=<class 'str'>, raise_=True)[source]

Return o if already a str, otherwise return the string value for o. If o is None or an empty string, return default instead.

If o cannot be converted to an str, raise an error if raise_ is true, other return default instead.

dataclass_wizard.utils.type_conv.as_time(o: typing.Union[str, datetime.time], 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-in fromisoformat method.

  • time: Return object o if it’s already of this type or

    sub-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.

dataclass_wizard.utils.type_conv.as_timedelta(o: typing.Union[str, dataclass_wizard.type_def.N, datetime.timedelta], 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 a float and assume it’s in seconds. Otherwise, we convert strings via the pytimeparse.parse function.

  • int or float: A numeric value is assumed to be in seconds. In this case, it is passed in to the constructor like timedelta(seconds=...)

  • timedelta: Return object o if it’s already of this type or

    sub-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.

dataclass_wizard.utils.type_conv.date_to_timestamp(d: datetime.date) int[source]

Retrieves the epoch timestamp of a date object, as an int

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

Module contents