How to use the dataclasses.fields 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 facebookresearch / ReAgent / ml / rl / parameters.py View on Github external
def param_hash(p):
    """
    Use this to make parameters hashable. This is required because __hash__()
    is not inherited when subclass redefines __eq__(). We only need this when
    the parameter dataclass has a list or dict field.
    """
    return hash(tuple(_hash_field(getattr(p, f.name)) for f in dataclasses.fields(p)))
github konradhalas / dacite / dacite.py View on Github external
def _validate_config_field_name(data_class: Type[T], config: Config, parameter: str) -> None:
    data_class_fields = {field.name for field in fields(data_class)}
    for data_class_field in getattr(config, parameter):
        if '.' not in data_class_field:
            if data_class_field not in data_class_fields:
                raise InvalidConfigurationError(
                    parameter=parameter,
                    available_choices=data_class_fields,
                    value=data_class_field,
                )
github quantmind / aio-openapi / openapi / data / dump.py View on Github external
def dump_dataclass(schema: type, data: Optional[Dict] = None) -> Dict:
    """Dump a dictionary of data with a given dataclass dump functions
    If the data is not given, the schema object is assumed to be
    an instance of a dataclass.
    """
    data = asdict(schema) if data is None else data
    cleaned = {}
    fields_ = {f.name: f for f in fields(schema)}
    for name, value in iter_items(data):
        if name not in fields_ or is_nothing(value):
            continue
        field = fields_[name]
        dump_value = field.metadata.get(DUMP)
        if dump_value:
            value = dump_value(value)
        cleaned[field.name] = dump(field.type, value)

    return cleaned
github felix-hilden / spotipy / tekore / _model / serialise.py View on Github external
def member_repr(dataclass_type) -> str:
    """Construct representation of fields of type Model."""
    v_fields = sorted(fields(dataclass_type), key=lambda f: f.name)
    joined = ', '.join(f.name for f in v_fields)
    return dataclass_type.__name__ + '(' + joined + ')'
github Instagram / LibCST / libcst / matchers / _matcher_base.py View on Github external
return None

    # Now, check if this is a lambda matcher.
    if isinstance(matcher, MatchIfTrue):
        return {} if matcher.func(node) else None

    if isinstance(matcher, (MatchMetadata, MatchMetadataIfTrue)):
        return _metadata_matches(node, matcher, metadata_lookup)

    # Now, check that the node and matcher classes are the same.
    if node.__class__.__name__ != matcher.__class__.__name__:
        return None

    # Now, check that the children match for each attribute.
    all_captures = {}
    for field in fields(matcher):
        if field.name == "_metadata":
            # We don't care about this field, its a dataclasses implementation detail.
            continue
        elif field.name == "metadata":
            # Special field we respect for matching metadata on a particular node.
            desired = getattr(matcher, field.name)
            if isinstance(desired, DoNotCareSentinel):
                # We don't care about this
                continue
            metadata_capture = _metadata_matches(node, desired, metadata_lookup)
            if metadata_capture is None:
                return None
            all_captures = {**all_captures, **metadata_capture}
        else:
            desired = getattr(matcher, field.name)
            actual = getattr(node, field.name)
github edgedb / edgedb / edb / server / config / types.py View on Github external
def from_pyvalue(cls, data, *, allow_missing=False):
        if not isinstance(data, dict):
            raise cls._err(f'expected a dict value, got {type(data)!r}')

        spec = config.get_settings()

        data = dict(data)
        tname = data.pop('_tname', None)
        if tname is not None:
            if '::' in tname:
                tname = s_name.Name(tname).name
            cls = spec.get_type_by_name(tname)

        fields = {f.name: f for f in dataclasses.fields(cls)}

        items = {}
        inv_keys = []
        for fieldname, value in data.items():
            field = fields.get(fieldname)
            if field is None:
                if value is None:
                    # This may happen when data is produced by
                    # a polymorphic config query.
                    pass
                else:
                    inv_keys.append(fieldname)

                continue

            f_type = field.type
github danielgtaylor / python-betterproto / src / betterproto / __init__.py View on Github external
def __init__(self, cls: Type["Message"]):
        by_field = {}
        by_group: Dict[str, Set] = {}
        by_field_name = {}
        by_field_number = {}

        fields = dataclasses.fields(cls)
        for field in fields:
            meta = FieldMetadata.get(field)

            if meta.group:
                # This is part of a one-of group.
                by_field[field.name] = meta.group

                by_group.setdefault(meta.group, set()).add(field)

            by_field_name[field.name] = meta
            by_field_number[meta.number] = field.name

        self.oneof_group_by_field = by_field
        self.oneof_field_by_group = by_group
        self.field_name_by_number = by_field_number
        self.meta_by_field_name = by_field_name
github cipriantarta / typegql / typegql / core / builder.py View on Github external
def get_fields(self, graph: Type, is_mutation=False) -> Dict[str, Union[GraphQLField, GraphQLInputField]]:
        result: Dict[str, Union[GraphQLField, GraphQLInputField]] = dict()
        hints = get_type_hints(graph)
        if not is_dataclass(graph):
            raise ValueError(f'Expected dataclass for {graph}.')
        for field in fields(graph):
            if field.name.startswith('_') or field.metadata.get('skip') is True:
                continue
            _type = hints.get(field.name, field.type)
            if is_optional(_type):
                _type = _type.__args__[0]
            if is_mutation and self.is_readonly(field):
                continue

            graph_type = self.map_type(_type, is_mutation=is_mutation)
            if not graph_type:
                continue

            if self.is_required(field):
                graph_type = graphql.GraphQLNonNull(graph_type)
            args = self.arguments(field.metadata.get('arguments'), self.camelcase)
            if is_connection(_type):
github seandstewart / typical / typic / coercer.py View on Github external
See Also
        --------
        :py:class:`ResolvedAnnotation`
        """

        if not any(
            (inspect.ismethod(obj), inspect.isfunction(obj), inspect.isclass(obj))
        ):
            obj = type(obj)

        sig = cached_signature(obj)
        hints = cached_type_hints(obj)
        params: Mapping[str, inspect.Parameter] = sig.parameters
        fields: Mapping[str, dataclasses.Field] = {}
        if dataclasses.is_dataclass(obj):
            fields = {f.name: f for f in dataclasses.fields(obj)}
        ann = {}
        for name in params.keys() | hints.keys():
            param = params.get(name)
            hint = hints.get(name)
            field = fields.get(name)
            annotation = hint or param.annotation  # type: ignore
            annotation = resolve_supertype(annotation)
            param = param or inspect.Parameter(
                name,
                inspect.Parameter.POSITIONAL_OR_KEYWORD,
                default=_empty,
                annotation=hint or annotation,
            )
            if repr(param.default) == "":
                param = param.replace(default=_empty)
            if annotation is ClassVar: