How to use the dataclasses.MISSING 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 lebrice / SimpleParsing / simple_parsing / utils.py View on Github external
def default_value(field: dataclasses.Field) -> Union[T, _MISSING_TYPE]:
    """Returns the default value of a field in a dataclass, if available.
    When not available, returns `dataclasses.MISSING`.

    Args:
        field (dataclasses.Field): The dataclasses.Field to get the default value of.

    Returns:
        Union[T, _MISSING_TYPE]: The default value for that field, if present, or None otherwise.
    """
    if field.default is not dataclasses.MISSING:
        return field.default
    elif field.default_factory is not dataclasses.MISSING:  # type: ignore
        constructor = field.default_factory # type: ignore
        return constructor()
    else:
        return dataclasses.MISSING
github strawberry-graphql / strawberry / strawberry / field.py View on Github external
name=None,
        description=None,
        metadata=None,
        permission_classes=None
    ):
        self.field_name = name
        self.field_description = description
        self.field_resolver = resolver
        self.is_subscription = is_subscription
        self.is_input = is_input
        self.field_permission_classes = permission_classes

        super().__init__(
            # TODO:
            default=dataclasses.MISSING,
            default_factory=dataclasses.MISSING,
            init=is_input,
            repr=True,
            hash=None,
            # TODO: this needs to be False when init is False
            # we could turn it to True when and if we have a default
            # probably can't be True when passing a resolver
            compare=is_input,
            metadata=metadata,
        )
github s-knibbs / dataclasses-jsonschema / dataclasses_jsonschema / __init__.py View on Github external
field_meta.default = cls._encode_field(field.type, default_value, omit_none=False)
            required = False
        if field.metadata is not None:
            if "examples" in field.metadata:
                field_meta.examples = [
                    cls._encode_field(field.type, example, omit_none=False) for example in field.metadata["examples"]
                ]
            if "extensions" in field.metadata:
                field_meta.extensions = field.metadata["extensions"]
            if "description" in field.metadata:
                field_meta.description = field.metadata["description"]
            if "title" in field.metadata:
                field_meta.title = field.metadata["title"]
            if schema_type == SchemaType.OPENAPI_3:
                field_meta.read_only = field.metadata.get("read_only")
                if field_meta.read_only and default_value is MISSING:
                    warnings.warn(f"Read-only fields should have a default value")
                field_meta.write_only = field.metadata.get("write_only")
        return field_meta, required
github samuelcolvin / pydantic / pydantic / dataclasses.py View on Github external
raise validation_error
        object.__setattr__(self, '__dict__', d)
        object.__setattr__(self, '__initialised__', True)
        if post_init_post_parse is not None:
            post_init_post_parse(self, *initvars)

    _cls.__post_init__ = _pydantic_post_init
    cls = dataclasses._process_class(_cls, init, repr, eq, order, unsafe_hash, frozen)  # type: ignore

    fields: Dict[str, Any] = {}
    for field in dataclasses.fields(cls):

        if field.default != dataclasses.MISSING:
            field_value = field.default
        # mypy issue 7020 and 708
        elif field.default_factory != dataclasses.MISSING:  # type: ignore
            field_value = field.default_factory()  # type: ignore
        else:
            field_value = Required

        fields[field.name] = (field.type, field_value)

    validators = gather_all_validators(cls)
    cls.__pydantic_model__ = create_model(
        cls.__name__, __config__=config, __module__=_cls.__module__, __validators__=validators, **fields
    )

    cls.__initialised__ = False
    cls.__validate__ = classmethod(_validate_dataclass)
    cls.__get_validators__ = classmethod(_get_validators)
    if post_init_original:
        cls.__post_init_original__ = post_init_original
github lebrice / SimpleParsing / simple_parsing / wrappers / field_wrapper.py View on Github external
def default(self) -> Any:
        """ Either a single default value, when parsing a single argument, or
        the list of default values, when this argument is reused multiple times
        (which only happens with the `ConflictResolution.ALWAYS_MERGE` option).

        In order of increasing priority, this could either be:
        1. The default attribute of the field
        2. the value of the corresponding attribute on the parent,
        if it has a default value
        """
        if self._default is not None:
            return self._default

        default: Any = utils.default_value(self.field)

        if default is dataclasses.MISSING:
            default = None

        if self.action == "store_true" and default is None:
            default = False
        if self.action == "store_false" and default is None:
            default = True

        if self.parent.defaults:
            # if the dataclass holding this field has a default value (either
            # when passed  manually or by nesting), use the corresponding
            # attribute on that default instance.
            defaults = []
            for default_dataclass_instance in self.parent.defaults:
                parent_value = getattr(default_dataclass_instance, self.name)
                defaults.append(parent_value)
            default = defaults[0] if len(defaults) == 1 else defaults
github reckonsys / pgorm / pgorm / fields.py View on Github external
def __init__(
            self, default=MISSING, default_factory=MISSING, init=True,
            repr=True, hash=None, compare=True):
        # init=True because of the warning:
        # It is expected that init=False fields will be rarely and judiciously used  # noqa
        # https://docs.python.org/3/library/dataclasses.html#dataclasses.replace  # noqa

        # It is an error to specify both default and default_factory.
        # https://github.com/python/cpython/blob/2d88e63bfcf7bccba925ab80b3f47ccf8b7aefa8/Lib/dataclasses.py#L331  # noqa
        if default is not MISSING and default_factory is not MISSING:
            raise ValueError('cannot specify both default and default_factory')
        if default is MISSING and default_factory is MISSING:
            default = self.py_type()
        metadata = {'py_type': self.py_type, 'pg_type': self.pg_type}
        super(Field, self).__init__(
            default, default_factory, init, repr, hash, compare, metadata)
github raiden-network / raiden / raiden / storage / serialization / dataclass.py View on Github external
def wrapper(cls):
        cls = stdlib_dataclass(  # type: ignore
            cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen
        )
        #
        type_field = Field(
            default=MISSING,
            default_factory=MISSING,
            init=False,
            hash=None,
            repr=False,
            compare=False,
            metadata=None,
        )
        type_field.name = "type_"
        type_field._field_type = _FIELD
        cls.__dataclass_fields__["type_"] = type_field
        cls.type_ = class_type(cls)
        cls = dataclass_json(cls)

        return cls
github janLo / wallabag-kindle-consumer / wallabag_kindle_consumer / config.py View on Github external
def from_env():
        logger.info("Read config from environment")
        tmp = {}
        missing = []
        for field in dataclasses.fields(Config):
            if field.name.upper() in os.environ:
                tmp[field.name] = field.type(os.environ[field.name.upper()])
            else:
                if field.default is dataclasses.MISSING:
                    missing.append(field.name.upper())

        if 0 != len(missing):
            logger.warn("Environment config does not contain configs for: {lst}", lst=", ".join(missing))
            return None

        return Config(**tmp)
github dotnet / performance / src / benchmarks / gc / src / commonlib / parse_and_serialize.py View on Github external
def _get_field(fld: Field[object]) -> Result[str, object]:
                if fld.name in d:
                    return _try_yaml_to_typed(
                        fld.type, d[fld.name], yaml_file_path, child(fld.name)
                    )
                else:
                    if all_optional:
                        return Ok(None)
                    else:
                        assert fld.default not in (
                            MISSING,
                            NO_DEFAULT,
                        ), f"At {desc}: Did not find field {fld.name} (and it has no default)"
                        return Ok(fld.default)