How to use the dataclasses._MISSING_TYPE function in dataclasses

To help you get started, we’ve selected a few dataclasses examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ltworf / typedload / typedload / dataloader.py View on Github external
def _namedtupleload(l: Loader, value: Dict[str, Any], type_) -> Tuple:
    """
    This loads a Dict[str, Any] into a NamedTuple.
    """
    if not hasattr(type_, '__dataclass_fields__'):
        fields = set(type_.__annotations__.keys())
        optional_fields = set(getattr(type_, '_field_defaults', {}).keys())
        type_hints = type_.__annotations__
    else:
        #dataclass
        import dataclasses
        fields = set(type_.__dataclass_fields__.keys())
        optional_fields = {k for k,v in type_.__dataclass_fields__.items() if not (isinstance(getattr(v, 'default', dataclasses._MISSING_TYPE()), dataclasses._MISSING_TYPE) and isinstance(getattr(v, 'default_factory', dataclasses._MISSING_TYPE()), dataclasses._MISSING_TYPE))}
        type_hints = {k: v.type for k,v in type_.__dataclass_fields__.items()}

        #Name mangling

        # Prepare the list of the needed name changes
        transforms = []  # type: List[Tuple[str, str]]
        for field in fields:
            if type_.__dataclass_fields__[field].metadata:
                name = type_.__dataclass_fields__[field].metadata.get('name')
                if name:
                    transforms.append((field, name))
        # Do the needed name changes
        if transforms:
            value = value.copy()
            for pyname, dataname in transforms:
                if dataname in value:
github dfurtado / dataclass-csv / dataclass_csv / dataclass_reader.py View on Github external
def _get_optional_fields(self):
        return [
            field.name
            for field in dataclasses.fields(self.cls)
            if not isinstance(field.default, dataclasses._MISSING_TYPE)
            or not isinstance(field.default_factory, dataclasses._MISSING_TYPE)
        ]
github jacebrowning / datafiles / datafiles / mappers.py View on Github external
import inspect
import os
from pathlib import Path
from typing import Any, Dict, Optional

import log
from cached_property import cached_property

from . import formats, hooks
from .config import Meta
from .converters import Converter, List, map_type
from .utils import prettify, recursive_update


Trilean = Optional[bool]
Missing = dataclasses._MISSING_TYPE


class Mapper:
    def __init__(
        self,
        instance: Any,
        *,
        attrs: Dict,
        pattern: Optional[str],
        manual: bool,
        defaults: bool,
        auto_load: bool,
        auto_save: bool,
        auto_attr: bool,
        root: Optional[Mapper] = None,
    ) -> None:
github opensight-cv / opensight / opsi / webserver / serialize.py View on Github external
def get_field_type(field) -> InputOutputF:
    io = get_type(field.type)
    if field.default and type(field.default) is not _MISSING_TYPE:
        io.params["default"] = field.default
    return io
github lebrice / SimpleParsing / simple_parsing / helpers / fields.py View on Github external
elif action == "store_true":
            if default not in {MISSING, False}:
                raise RuntimeError("default should either not be passed or set "
                                   "to False when using the store_true action.")
            default = False  # type: ignore

    if default is not MISSING:
        return dataclasses.field(  # type: ignore
            default=default,
            init=init,
            repr=repr,
            hash=hash,
            compare=compare,
            metadata=_metadata
        )
    elif not isinstance(default_factory, dataclasses._MISSING_TYPE):
        return dataclasses.field(
            default_factory=default_factory,
            init=init,
            repr=repr,
            hash=hash,
            compare=compare,
            metadata=_metadata
        )
    else:
        return dataclasses.field(
            init=init,
            repr=repr,
            hash=hash,
            compare=compare,
            metadata=_metadata
        )
github lidatong / dataclasses-json / dataclasses_json / undefined.py View on Github external
def _get_default(catch_all_field: Field) -> Any:
        # access to the default factory currently causes
        # a false-positive mypy error (16. Dec 2019):
        # https://github.com/python/mypy/issues/6910

        # noinspection PyProtectedMember
        has_default = not isinstance(catch_all_field.default,
                                     dataclasses._MISSING_TYPE)
        # noinspection PyProtectedMember
        has_default_factory = not isinstance(catch_all_field.default_factory,
                                             # type: ignore
                                             dataclasses._MISSING_TYPE)
        default_value = _CatchAllUndefinedParameters._SentinelNoDefault
        if has_default:
            default_value = catch_all_field.default
        elif has_default_factory:
            # This might be unwanted if the default factory constructs
            # something expensive,
            # because we have to construct it again just for this test
            default_value = catch_all_field.default_factory()  # type: ignore

        return default_value
github ericvsmith / dataclasses / dataclasses.py View on Github external
# Raised when an attempt is made to modify a frozen class.
class FrozenInstanceError(AttributeError): pass

# A sentinel object for default values to signal that a default
# factory will be used.  This is given a nice repr() which will appear
# in the function signature of dataclasses' constructors.
class _HAS_DEFAULT_FACTORY_CLASS:
    def __repr__(self):
        return ''
_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()

# A sentinel object to detect if a parameter is supplied or not.  Use
# a class to give it a better repr.
class _MISSING_TYPE:
    pass
MISSING = _MISSING_TYPE()

# Since most per-field metadata will be unused, create an empty
# read-only proxy that can be shared among all fields.
_EMPTY_METADATA = types.MappingProxyType({})

# Markers for the various kinds of fields and pseudo-fields.
class _FIELD_BASE:
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name
_FIELD = _FIELD_BASE('_FIELD')
_FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR')
_FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR')

# The name of an attribute on the class where we store the Field
github dfurtado / dataclass-csv / dataclass_csv / dataclass_reader.py View on Github external
def _get_default_value(self, field):
        return (
            field.default
            if not isinstance(field.default, dataclasses._MISSING_TYPE)
            else field.default_factory()
        )