Module dataclasses_json

View Source
# flake8: noqa

from dataclasses_json.api import (DataClassJsonMixin,

                                  dataclass_json)

from dataclasses_json.cfg import (config, global_config,

                                  Exclude, LetterCase)

from dataclasses_json.undefined import CatchAll, Undefined

__all__ = ['DataClassJsonMixin', 'LetterCase', 'dataclass_json',

           'config', 'global_config', 'Exclude',

           'CatchAll', 'Undefined']

Sub-modules

Variables

CatchAll
global_config

Functions

config

def config(
    metadata: dict = None,
    *,
    encoder: Callable = None,
    decoder: Callable = None,
    mm_field: marshmallow.fields.Field = None,
    letter_case: Union[Callable[[str], str], dataclasses_json.cfg.LetterCase, NoneType] = None,
    undefined: Union[str, dataclasses_json.undefined.Undefined, NoneType] = None,
    field_name: str = None,
    exclude: Union[Callable[[str, ~T], bool], dataclasses_json.cfg.Exclude, NoneType] = None
) -> Dict[str, dict]
View Source
def config(metadata: dict = None, *,

           # TODO: these can be typed more precisely

           # Specifically, a Callable[A, B], where `B` is bound as a JSON type

           encoder: Callable = None,

           decoder: Callable = None,

           mm_field: MarshmallowField = None,

           letter_case: Union[Callable[[str], str], LetterCase, None] = None,

           undefined: Optional[Union[str, Undefined]] = None,

           field_name: str = None,

           exclude: Union[Callable[[str, T], bool], Exclude, None] = None,

           ) -> Dict[str, dict]:

    if metadata is None:

        metadata = {}

    lib_metadata = metadata.setdefault('dataclasses_json', {})

    if encoder is not None:

        lib_metadata['encoder'] = encoder

    if decoder is not None:

        lib_metadata['decoder'] = decoder

    if mm_field is not None:

        lib_metadata['mm_field'] = mm_field

    if field_name is not None:

        if letter_case is not None:

            @functools.wraps(letter_case)  # type:ignore

            def override(_, _letter_case=letter_case, _field_name=field_name):

                return _letter_case(_field_name)

        else:

            def override(_, _field_name=field_name):  # type:ignore

                return _field_name

        letter_case = override

    if letter_case is not None:

        lib_metadata['letter_case'] = letter_case

    if undefined is not None:

        # Get the corresponding action for undefined parameters

        if isinstance(undefined, str):

            if not hasattr(Undefined, undefined.upper()):

                valid_actions = list(action.name for action in Undefined)

                raise UndefinedParameterError(

                    f"Invalid undefined parameter action, "

                    f"must be one of {valid_actions}")

            undefined = Undefined[undefined.upper()]

        lib_metadata['undefined'] = undefined

    if exclude is not None:

        lib_metadata['exclude'] = exclude

    return metadata

dataclass_json

def dataclass_json(
    _cls=None,
    *,
    letter_case=None,
    undefined: Union[str, dataclasses_json.undefined.Undefined, NoneType] = None
)

Based on the code in the dataclasses module to handle optional-parens decorators. See example below:

@dataclass_json @dataclass_json(letter_case=LetterCase.CAMEL) class Example: ...

View Source
def dataclass_json(_cls=None, *, letter_case=None,

                   undefined: Optional[Union[str, Undefined]] = None):

    """

    Based on the code in the `dataclasses` module to handle optional-parens

    decorators. See example below:

    @dataclass_json

    @dataclass_json(letter_case=LetterCase.CAMEL)

    class Example:

        ...

    """

    def wrap(cls):

        return _process_class(cls, letter_case, undefined)

    if _cls is None:

        return wrap

    return wrap(_cls)

Classes

DataClassJsonMixin

class DataClassJsonMixin(
    /,
    *args,
    **kwargs
)

DataClassJsonMixin is an ABC that functions as a Mixin.

As with other ABCs, it should not be instantiated directly.

View Source
class DataClassJsonMixin(abc.ABC):

    """

    DataClassJsonMixin is an ABC that functions as a Mixin.

    As with other ABCs, it should not be instantiated directly.

    """

    dataclass_json_config = None

    def to_json(self,

                *,

                skipkeys: bool = False,

                ensure_ascii: bool = True,

                check_circular: bool = True,

                allow_nan: bool = True,

                indent: Optional[Union[int, str]] = None,

                separators: Tuple[str, str] = None,

                default: Callable = None,

                sort_keys: bool = False,

                **kw) -> str:

        return json.dumps(self.to_dict(encode_json=False),

                          cls=_ExtendedEncoder,

                          skipkeys=skipkeys,

                          ensure_ascii=ensure_ascii,

                          check_circular=check_circular,

                          allow_nan=allow_nan,

                          indent=indent,

                          separators=separators,

                          default=default,

                          sort_keys=sort_keys,

                          **kw)

    @classmethod

    def from_json(cls: Type[A],

                  s: JsonData,

                  *,

                  parse_float=None,

                  parse_int=None,

                  parse_constant=None,

                  infer_missing=False,

                  **kw) -> A:

        kvs = json.loads(s,

                         parse_float=parse_float,

                         parse_int=parse_int,

                         parse_constant=parse_constant,

                         **kw)

        return cls.from_dict(kvs, infer_missing=infer_missing)

    @classmethod

    def from_dict(cls: Type[A],

                  kvs: Json,

                  *,

                  infer_missing=False) -> A:

        return _decode_dataclass(cls, kvs, infer_missing)

    def to_dict(self, encode_json=False) -> Dict[str, Json]:

        return _asdict(self, encode_json=encode_json)

    @classmethod

    def schema(cls: Type[A],

               *,

               infer_missing: bool = False,

               only=None,

               exclude=(),

               many: bool = False,

               context=None,

               load_only=(),

               dump_only=(),

               partial: bool = False,

               unknown=None) -> SchemaType:

        Schema = build_schema(cls, DataClassJsonMixin, infer_missing, partial)

        if unknown is None:

            undefined_parameter_action = _undefined_parameter_action_safe(cls)

            if undefined_parameter_action is not None:

                # We can just make use of the same-named mm keywords

                unknown = undefined_parameter_action.name.lower()

        return Schema(only=only,

                      exclude=exclude,

                      many=many,

                      context=context,

                      load_only=load_only,

                      dump_only=dump_only,

                      partial=partial,

                      unknown=unknown)

Ancestors (in MRO)

  • abc.ABC

Class variables

dataclass_json_config

Static methods

from_dict
def from_dict(
    kvs: Union[dict, list, str, int, float, bool, NoneType],
    *,
    infer_missing=False
) -> ~A
View Source
    @classmethod

    def from_dict(cls: Type[A],

                  kvs: Json,

                  *,

                  infer_missing=False) -> A:

        return _decode_dataclass(cls, kvs, infer_missing)
from_json
def from_json(
    s: Union[str, bytes, bytearray],
    *,
    parse_float=None,
    parse_int=None,
    parse_constant=None,
    infer_missing=False,
    **kw
) -> ~A
View Source
    @classmethod

    def from_json(cls: Type[A],

                  s: JsonData,

                  *,

                  parse_float=None,

                  parse_int=None,

                  parse_constant=None,

                  infer_missing=False,

                  **kw) -> A:

        kvs = json.loads(s,

                         parse_float=parse_float,

                         parse_int=parse_int,

                         parse_constant=parse_constant,

                         **kw)

        return cls.from_dict(kvs, infer_missing=infer_missing)
schema
def schema(
    *,
    infer_missing: bool = False,
    only=None,
    exclude=(),
    many: bool = False,
    context=None,
    load_only=(),
    dump_only=(),
    partial: bool = False,
    unknown=None
) -> dataclasses_json.mm.SchemaF[~A]
View Source
    @classmethod

    def schema(cls: Type[A],

               *,

               infer_missing: bool = False,

               only=None,

               exclude=(),

               many: bool = False,

               context=None,

               load_only=(),

               dump_only=(),

               partial: bool = False,

               unknown=None) -> SchemaType:

        Schema = build_schema(cls, DataClassJsonMixin, infer_missing, partial)

        if unknown is None:

            undefined_parameter_action = _undefined_parameter_action_safe(cls)

            if undefined_parameter_action is not None:

                # We can just make use of the same-named mm keywords

                unknown = undefined_parameter_action.name.lower()

        return Schema(only=only,

                      exclude=exclude,

                      many=many,

                      context=context,

                      load_only=load_only,

                      dump_only=dump_only,

                      partial=partial,

                      unknown=unknown)

Methods

to_dict
def to_dict(
    self,
    encode_json=False
) -> Dict[str, Union[dict, list, str, int, float, bool, NoneType]]
View Source
    def to_dict(self, encode_json=False) -> Dict[str, Json]:

        return _asdict(self, encode_json=encode_json)
to_json
def to_json(
    self,
    *,
    skipkeys: bool = False,
    ensure_ascii: bool = True,
    check_circular: bool = True,
    allow_nan: bool = True,
    indent: Union[int, str, NoneType] = None,
    separators: Tuple[str, str] = None,
    default: Callable = None,
    sort_keys: bool = False,
    **kw
) -> str
View Source
    def to_json(self,

                *,

                skipkeys: bool = False,

                ensure_ascii: bool = True,

                check_circular: bool = True,

                allow_nan: bool = True,

                indent: Optional[Union[int, str]] = None,

                separators: Tuple[str, str] = None,

                default: Callable = None,

                sort_keys: bool = False,

                **kw) -> str:

        return json.dumps(self.to_dict(encode_json=False),

                          cls=_ExtendedEncoder,

                          skipkeys=skipkeys,

                          ensure_ascii=ensure_ascii,

                          check_circular=check_circular,

                          allow_nan=allow_nan,

                          indent=indent,

                          separators=separators,

                          default=default,

                          sort_keys=sort_keys,

                          **kw)

Exclude

class Exclude(
    /,
    *args,
    **kwargs
)

Pre-defined constants for exclusion. By default, fields are configured to be included.

View Source
class Exclude:

    """

    Pre-defined constants for exclusion. By default, fields are configured to

    be included.

    """

    ALWAYS: Callable[[T], bool] = lambda _: True

    NEVER: Callable[[T], bool] = lambda _: False

Methods

ALWAYS
def ALWAYS(
    _
)
View Source
    ALWAYS: Callable[[T], bool] = lambda _: True
NEVER
def NEVER(
    _
)
View Source
    NEVER: Callable[[T], bool] = lambda _: False

LetterCase

class LetterCase(
    /,
    *args,
    **kwargs
)

An enumeration.

View Source
class LetterCase(Enum):

    CAMEL = camelcase

    KEBAB = spinalcase

    SNAKE = snakecase

    PASCAL = pascalcase

Ancestors (in MRO)

  • enum.Enum

Class variables

CAMEL
KEBAB
PASCAL
SNAKE
name
value

Undefined

class Undefined(
    /,
    *args,
    **kwargs
)

Choose the behavior what happens when an undefined parameter is encountered during class initialization.

View Source
class Undefined(Enum):

    """

    Choose the behavior what happens when an undefined parameter is encountered

    during class initialization.

    """

    INCLUDE = _CatchAllUndefinedParameters

    RAISE = _RaiseUndefinedParameters

    EXCLUDE = _IgnoreUndefinedParameters

Ancestors (in MRO)

  • enum.Enum

Class variables

EXCLUDE
INCLUDE
RAISE
name
value