Python dataclasses.Field() Examples

The following are 12 code examples of dataclasses.Field(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dataclasses , or try the search function .
Example #1
Source File: configuration.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def resolve_defaults(func):
    """
    Use this decorator to resolve default field values in the constructor.
    """

    func_params = list(signature(func).parameters.values())

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if len(args) > len(func_params):
            raise ValueError(
                f"There are {len(func_params)} parameters in total, "
                f"but args is {len(args)} long. \n"
                f"{args}"
            )
        # go through unprovided default kwargs
        for p in func_params[len(args) :]:
            # only resolve defaults for Fields
            if isinstance(p.default, Field):
                if p.name not in kwargs:
                    kwargs[p.name] = _resolve_default(p.default)
        return func(*args, **kwargs)

    return wrapper 
Example #2
Source File: undefined.py    From dataclasses-json with MIT License 6 votes vote down vote up
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 
Example #3
Source File: configs.py    From trinity with MIT License 6 votes vote down vote up
def _decoder(
    # NOTE: mypy incorrectly thinks `Field` is a generic type
    data: Dict[str, EncodedConfigTypes],
    fields: Collection[Field],  # type: ignore
) -> Iterable[Tuple[str, ConfigTypes]]:
    # NOTE: this code is unwieldly but it satisfies `mypy`
    for field in fields:
        if field.type is Gwei:
            yield field.name, Gwei(cast(int, data[field.name]))
        elif field.type is Slot:
            yield field.name, Slot(cast(int, data[field.name]))
        elif field.type is Epoch:
            yield field.name, Epoch(cast(int, data[field.name]))
        elif field.type is Second:
            yield field.name, Second(cast(int, data[field.name]))
        elif field.type is bytes:
            yield field.name, decode_hex(cast(str, data[field.name]))
        else:
            yield field.name, int(data[field.name]) 
Example #4
Source File: __init__.py    From dataclasses-jsonschema with MIT License 5 votes vote down vote up
def _get_fields(cls, base_fields=True) -> List[JsonSchemaField]:

        def _get_fields_uncached():
            dataclass_bases = [
                klass for klass in cls.__bases__ if is_dataclass(klass) and issubclass(klass, JsonSchemaMixin)
            ]
            base_fields_types = set()
            for base in dataclass_bases:
                base_fields_types |= {(f.name, f.type) for f in fields(base)}

            mapped_fields = []
            type_hints = get_type_hints(cls)
            for f in fields(cls):
                # Skip internal fields
                if f.name.startswith("__") or (not base_fields and (f.name, f.type) in base_fields_types):
                    continue
                # Note fields() doesn't resolve forward refs
                f.type = type_hints[f.name]
                mapped_fields.append(JsonSchemaField(f, cls.field_mapping().get(f.name, f.name)))

            if cls.__serialise_properties:
                include_properties = None
                if isinstance(cls.__serialise_properties, tuple):
                    include_properties = set(cls.__serialise_properties)

                members = inspect.getmembers(cls, inspect.isdatadescriptor)
                for name, member in members:
                    if name != "__weakref__" and (include_properties is None or name in include_properties):
                        f = Field(MISSING, None, None, None, None, None, None)
                        f.name = name
                        f.type = member.fget.__annotations__['return']
                        mapped_fields.append(JsonSchemaField(f, name, is_property=True))

            return mapped_fields

        if not base_fields:
            return _get_fields_uncached()

        if not cls.__mapped_fields:
            cls.__mapped_fields = _get_fields_uncached()
        return cls.__mapped_fields  # type: ignore 
Example #5
Source File: __init__.py    From dataclasses-jsonschema with MIT License 5 votes vote down vote up
def _get_field_meta(cls, field: Field, schema_type: SchemaType) -> Tuple[FieldMeta, bool]:
        required = True
        field_meta = FieldMeta(schema_type=schema_type)
        default_value = MISSING
        if field.default is not MISSING:
            # In case of default value given
            default_value = field.default
        elif field.default_factory is not MISSING and field.default_factory is not None:  # type: ignore
            # In case of a default factory given, we call it
            default_value = field.default_factory()  # type: ignore

        if default_value is not MISSING:
            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 
Example #6
Source File: patcher_configuration.py    From randovania with GNU General Public License v3.0 5 votes vote down vote up
def from_json_dict(cls, json_dict: dict) -> "PatcherConfiguration":
        kwargs = {}

        for field in dataclasses.fields(cls):
            field: dataclasses.Field = field
            if field.name in json_dict:
                kwargs[field.name] = field.type(json_dict[field.name])

        return PatcherConfiguration(**kwargs) 
Example #7
Source File: configuration.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _resolve_default(val):
    if not isinstance(val, Field):
        return val
    if val.default != MISSING:
        return val.default
    if val.default_factory != MISSING:
        return val.default_factory()
    raise ValueError("No default value") 
Example #8
Source File: __init__.py    From marshmallow_dataclass with MIT License 5 votes vote down vote up
def _proxied_class_schema(
    clazz: type, base_schema: Optional[Type[marshmallow.Schema]] = None
) -> Type[marshmallow.Schema]:

    try:
        # noinspection PyDataclass
        fields: Tuple[dataclasses.Field, ...] = dataclasses.fields(clazz)
    except TypeError:  # Not a dataclass
        try:
            return class_schema(dataclasses.dataclass(clazz), base_schema)
        except Exception:
            raise TypeError(
                f"{getattr(clazz, '__name__', repr(clazz))} is not a dataclass and cannot be turned into one."
            )

    # Copy all marshmallow hooks and whitelisted members of the dataclass to the schema.
    attributes = {
        k: v
        for k, v in inspect.getmembers(clazz)
        if hasattr(v, "__marshmallow_hook__") or k in MEMBERS_WHITELIST
    }
    # Update the schema members to contain marshmallow fields instead of dataclass fields
    attributes.update(
        (
            field.name,
            field_for_schema(
                field.type, _get_field_default(field), field.metadata, base_schema
            ),
        )
        for field in fields
        if field.init
    )

    schema_class = type(clazz.__name__, (_base_schema(clazz, base_schema),), attributes)
    return cast(Type[marshmallow.Schema], schema_class) 
Example #9
Source File: __init__.py    From marshmallow_dataclass with MIT License 5 votes vote down vote up
def _field_by_type(
    typ: Union[type, Any], base_schema: Optional[Type[marshmallow.Schema]]
) -> Optional[Type[marshmallow.fields.Field]]:
    return (
        base_schema and base_schema.TYPE_MAPPING.get(typ)
    ) or marshmallow.Schema.TYPE_MAPPING.get(typ) 
Example #10
Source File: __init__.py    From marshmallow_dataclass with MIT License 5 votes vote down vote up
def _get_field_default(field: dataclasses.Field):
    """
    Return a marshmallow default value given a dataclass default value

    >>> _get_field_default(dataclasses.field())
    <marshmallow.missing>
    """
    # Remove `type: ignore` when https://github.com/python/mypy/issues/6910 is fixed
    default_factory = field.default_factory  # type: ignore
    if default_factory is not dataclasses.MISSING:
        return default_factory
    elif field.default is dataclasses.MISSING:
        return marshmallow.missing
    return field.default 
Example #11
Source File: undefined.py    From dataclasses-json with MIT License 5 votes vote down vote up
def _get_catch_all_field(cls) -> Field:
        catch_all_fields = list(
            filter(lambda f: f.type == Optional[CatchAllVar], fields(cls)))
        number_of_catch_all_fields = len(catch_all_fields)
        if number_of_catch_all_fields == 0:
            raise UndefinedParameterError(
                "No field of type dataclasses_json.CatchAll defined")
        elif number_of_catch_all_fields > 1:
            raise UndefinedParameterError(
                f"Multiple catch-all fields supplied: "
                f"{number_of_catch_all_fields}.")
        else:
            return catch_all_fields[0] 
Example #12
Source File: __init__.py    From marshmallow_dataclass with MIT License 4 votes vote down vote up
def NewType(
    name: str,
    typ: Type[_U],
    field: Optional[Type[marshmallow.fields.Field]] = None,
    **kwargs,
) -> Callable[[_U], _U]:
    """NewType creates simple unique types
    to which you can attach custom marshmallow attributes.
    All the keyword arguments passed to this function will be transmitted
    to the marshmallow field constructor.

    >>> import marshmallow.validate
    >>> IPv4 = NewType('IPv4', str, validate=marshmallow.validate.Regexp(r'^([0-9]{1,3}\\.){3}[0-9]{1,3}$'))
    >>> @dataclass
    ... class MyIps:
    ...   ips: List[IPv4]
    >>> MyIps.Schema().load({"ips": ["0.0.0.0", "grumble grumble"]})
    Traceback (most recent call last):
    ...
    marshmallow.exceptions.ValidationError: {'ips': {1: ['String does not match expected pattern.']}}
    >>> MyIps.Schema().load({"ips": ["127.0.0.1"]})
    MyIps(ips=['127.0.0.1'])

    >>> Email = NewType('Email', str, field=marshmallow.fields.Email)
    >>> @dataclass
    ... class ContactInfo:
    ...   mail: Email = dataclasses.field(default="anonymous@example.org")
    >>> ContactInfo.Schema().load({})
    ContactInfo(mail='anonymous@example.org')
    >>> ContactInfo.Schema().load({"mail": "grumble grumble"})
    Traceback (most recent call last):
    ...
    marshmallow.exceptions.ValidationError: {'mail': ['Not a valid email address.']}
    """

    def new_type(x: _U):
        return x

    new_type.__name__ = name
    new_type.__supertype__ = typ  # type: ignore
    new_type._marshmallow_field = field  # type: ignore
    new_type._marshmallow_args = kwargs  # type: ignore
    return new_type