Python dataclasses.fields() Examples

The following are 30 code examples of dataclasses.fields(). 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: value_object.py    From python-clean-architecture with MIT License 7 votes vote down vote up
def __repr__(self):
        """
        Repr respects only fields which values are not default
        (practical decision for large dataclasses).
        """
        # noinspection PyDataclass
        fields = (
            (f.name, getattr(self, f.name), f.default)
            for f in dataclasses.fields(self)
        )
        fields_str = ', '.join(
            f"{name}={repr(value)}"
            for name, value, default in fields
            if value is not default
        )
        return f"{self.__class__.__qualname__}({fields_str})" 
Example #2
Source File: report.py    From professional-services with Apache License 2.0 6 votes vote down vote up
def __init__(self, config, step, timestamp, client=None, delete=False):

        # Init dataclass fields from SLO config and Error Budget Policy
        self.__set_fields(**config,
                          **step,
                          lambdas={
                              'slo_target': float,
                              'alerting_burn_rate_threshold': int
                          })

        # Set other fields
        self.window = int(step['measurement_window_seconds'])
        self.timestamp = int(timestamp)
        self.timestamp_human = utils.get_human_time(timestamp)

        # Get backend results
        result = self.run_backend(config, client=client, delete=delete)
        if result:
            self.build(step, result) 
Example #3
Source File: serializing.py    From clean-architecture with MIT License 6 votes vote down vote up
def to_json(dataclass_instance: Dataclass) -> str:
    data = {}
    for field in dataclasses.fields(type(dataclass_instance)):
        field_type, _ = _extract_type_if_optional(field.type)
        if field_type not in serializers:
            if issubclass(field_type, Enum):
                serializers[field_type] = lambda field: field.value
            else:
                raise Exception(f"Type {field_type} not supported")

        if getattr(dataclass_instance, field.name):
            data[field.name] = serializers[field_type](getattr(dataclass_instance, field.name))  # type: ignore
        else:
            data[field.name] = None

    return json.dumps(data) 
Example #4
Source File: bitpacking.py    From randovania with GNU General Public License v3.0 6 votes vote down vote up
def bit_pack_unpack(cls, decoder: BitPackDecoder, metadata):
        reference = metadata.get("reference")
        args = {}

        for field in dataclasses.fields(cls):
            if not field.init:
                continue

            should_decode = True
            if reference is not None:
                if not decode_bool(decoder):
                    item = getattr(reference, field.name)
                    should_decode = False

            if should_decode:
                item = _get_bit_pack_value_for_type(field.type).bit_pack_unpack(decoder, field.metadata)

            args[field.name] = item

        return cls(**args) 
Example #5
Source File: types.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def to_json_value(self):
        dct = {}
        dct['_tname'] = self.__class__.__name__

        for f in dataclasses.fields(self):
            f_type = f.type
            value = getattr(self, f.name)
            if (isinstance(f_type, type)
                    and issubclass(f_type, CompositeConfigType)
                    and value is not None):
                value = value.to_json_value()
            elif typing_inspect.is_generic_type(f_type):
                value = list(value)

            dct[f.name] = value

        return dct 
Example #6
Source File: serializing.py    From clean-architecture with MIT License 6 votes vote down vote up
def from_json(json_repr: dict, dataclass: Type[T]) -> T:
    data = {}
    for field in dataclasses.fields(dataclass):
        field_type, _ = _extract_type_if_optional(field.type)
        if field_type not in deserializers:
            if issubclass(field_type, Enum):
                deserializers[field_type] = field_type
            else:
                raise Exception(f"Type {field_type} not supported")

        if json_repr[field.name]:
            data[field.name] = deserializers[field_type](json_repr[field.name])  # type: ignore
        else:
            data[field.name] = None

    return dataclass(**data)  # type: ignore 
Example #7
Source File: generate.py    From podenv with Apache License 2.0 6 votes vote down vote up
def writeReferences() -> None:
    path = Path("docs/references/configuration.md")
    doc = path.read_text().split('\n')

    envblockstart = doc.index(
        'Name                 | Type            | '
        'Doc                                      |') + 2
    envblockend = doc[envblockstart:].index('') + envblockstart
    capblockstart = doc.index(
        'Name                 | Doc               '
        '                                         |') + 2
    capblockend = doc[capblockstart:].index('') + capblockstart

    envblock = ['{name:20s} | {type:15s} | {doc:40s} |'.format(
        name=(lambda s: re.sub('([A-Z]+)', r'-\1', s).lower())(f.name),
        type=f.type, doc=f.metadata.get('doc', ''))  # type: ignore
                for f in fields(Env)
                if not f.metadata.get('internal', False)]  # type: ignore
    capblock = ['{name:20s} | {doc:60s} |'.format(
        name=c[0], doc=c[1]) for c in Capabilities]
    newdoc = doc[:envblockstart] + envblock + doc[
        envblockend:capblockstart] + capblock + doc[capblockend:]
    update(path, "\n".join(newdoc)) 
Example #8
Source File: base.py    From dffml with MIT License 6 votes vote down vote up
def config(cls, config, *above):
        """
        Create the BaseConfig required to instantiate this class by parsing the
        config dict.
        """
        if getattr(cls, "CONFIG", None) is None:
            raise AttributeError(
                f"{cls.__qualname__} requires CONFIG property or implementation of config() classmethod"
            )
        # Build the arguments to the CONFIG class
        kwargs: Dict[str, Any] = {}
        for field in dataclasses.fields(cls.CONFIG):
            kwargs[field.name] = got = cls.config_get(
                config, above, field.name
            )
            if inspect.isclass(got) and issubclass(got, BaseConfigurable):
                try:
                    kwargs[field.name] = got.withconfig(
                        config, *above, *cls.add_label()
                    )
                except MissingConfig:
                    kwargs[field.name] = got.withconfig(
                        config, *above, *cls.add_label()[:-1]
                    )
        return cls.CONFIG(**kwargs) 
Example #9
Source File: cmd.py    From dffml with MIT License 6 votes vote down vote up
def __init__(self, extra_config=None, **kwargs) -> None:
        if not hasattr(self, "logger"):
            self.logger = logging.getLogger(
                "%s.%s"
                % (self.__class__.__module__, self.__class__.__qualname__)
            )
        if extra_config is None:
            extra_config = {}
        self.extra_config = extra_config

        for field in dataclasses.fields(self.CONFIG):
            arg = mkarg(field)
            if isinstance(arg, Arg):
                if not field.name in kwargs and "default" in arg:
                    kwargs[field.name] = arg["default"]
                if field.name in kwargs and not hasattr(self, field.name):
                    self.logger.debug(
                        "Setting %s = %r", field.name, kwargs[field.name]
                    )
                    setattr(self, field.name, kwargs[field.name])
                else:
                    self.logger.debug("Ignored %s", field.name) 
Example #10
Source File: dataclass_tools.py    From dataclasses with Apache License 2.0 6 votes vote down vote up
def add_slots(cls):
    # Need to create a new class, since we can't set __slots__
    #  after a class has been created.

    # Make sure __slots__ isn't already set.
    if '__slots__' in cls.__dict__:
        raise TypeError(f'{cls.__name__} already specifies __slots__')

    # Create a new dict for our new class.
    cls_dict = dict(cls.__dict__)
    field_names = tuple(f.name for f in dataclasses.fields(cls))
    cls_dict['__slots__'] = field_names
    for field_name in field_names:
        # Remove our attributes, if present. They'll still be
        #  available in _MARKER.
        cls_dict.pop(field_name, None)
    # Remove __dict__ itself.
    cls_dict.pop('__dict__', None)
    # And finally create the class.
    qualname = getattr(cls, '__qualname__', None)
    cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
    if qualname is not None:
        cls.__qualname__ = qualname
    return cls 
Example #11
Source File: report.py    From professional-services with Apache License 2.0 6 votes vote down vote up
def __set_fields(self, lambdas={}, **kwargs):
        """Set all fields in dataclasses from configs passed and apply function
        on values whose key match one in the dictionaries.

        Args:
            lambdas (dict): Dict {key: function} to apply a function on certain
            kwargs (dict): Dict of key / values to set in dataclass.
        """
        names = set(f.name for f in fields(self))
        for name in names:
            if name not in kwargs:
                continue
            value = kwargs[name]
            if name in lambdas.keys():
                value = lambdas[name](value)
            setattr(self, name, value) 
Example #12
Source File: flows.py    From spins-b with GNU General Public License v3.0 6 votes vote down vote up
def constant_field(**kwargs):
    """Marks a flow field as constant.

    Constant flow fields are not permitted to change value once set, and
    consequently, the gradient for these fields do not exist.

    Args:
        kwargs: Keyword arguments to pass to `dataclasses.field`.

    Returns:
        A dataclasses field where `metadata` has entry `"constant_field": True`.
    """
    if "metadata" not in kwargs:
        kwargs["metadata"] = {}
    kwargs["metadata"].update({"constant_field": True})
    return dataclasses.field(**kwargs) 
Example #13
Source File: types.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_transition(self, transition: Transition):
        if len(self) == 0:
            # remember which optional fields should be filled
            for f in self.optional_field_exist:
                val = getattr(transition, f, None)
                if val is not None:
                    self.optional_field_exist[f] = True

        # check that later additions also fill the same optional fields
        for f, should_exist in self.optional_field_exist.items():
            val = getattr(transition, f, None)
            if (val is not None) != should_exist:
                raise ValueError(
                    f"Field {f} given val {val} whereas should_exist is {should_exist}."
                )

        self.transitions.append(transition) 
Example #14
Source File: typed_json_dataclass.py    From typed-json-dataclass with MIT License 6 votes vote down vote up
def _contains_non_default_init_vars(cls, previous_classes=None):
        """Check whether this dataclass contains non-default init-only vars.

        Performs a recursive check through all fields that are declared as
        dataclasses to ensure that no nested dataclasses contain init-only
        variables. The ``previous_classes`` argument is a set of previously
        checked classes to prevent infinite recursion on recursive structures.

        :param previous_classes: The set of previously checked classes.
        """
        try:
            previous_classes.add(cls)
        except AttributeError:  # NoneType
            previous_classes = {cls}

        # The identify check (.. is MISSING) is fine, MISSING is a singleton
        has_init_vars = any(field.type == InitVar and field.default is MISSING
                            for field in cls.__dataclass_fields__.values())
        children_have_init_vars = any(
                child.type._contains_non_default_init_vars(previous_classes)
                for child in fields(cls)
                if (is_dataclass(child.type)
                    and child.type not in previous_classes))
        return has_init_vars or children_have_init_vars 
Example #15
Source File: io.py    From Pyslvs-UI with GNU Affero General Public License v3.0 6 votes vote down vote up
def restore_settings(self) -> None:
        """Restore Pyslvs settings."""
        prefer = Preferences()
        for field in fields(prefer):  # type: Field
            setting = self.settings.value(field.name, field.default)
            setattr(prefer, field.name, setting)
        # Specified solver setting
        kernel = ARGUMENTS.kernel
        if kernel:
            if kernel == "python_solvespace":
                prefer.planar_solver_option = 1
            elif kernel == "sketch_solve":
                prefer.planar_solver_option = 2
            elif kernel == "pyslvs":
                prefer.planar_solver_option = 0
            else:
                QMessageBox.warning(
                    self,
                    "Kernel not found",
                    f"No such kernel: {kernel}"
                )
        self.apply_preferences(prefer, force=True) 
Example #16
Source File: test_dataclasses.py    From dacite with MIT License 5 votes vote down vote up
def test_get_default_value_for_optional_field():
    @dataclass
    class X:
        i: Optional[int]

    value = get_default_value_for_field(field=fields(X)[0])

    assert value is None 
Example #17
Source File: cli.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def select_relevant_params(config_dict, ConfigClass):
    return {
        field.name: config_dict[field.name]
        for field in dataclasses.fields(ConfigClass)
        if field.name in config_dict
    } 
Example #18
Source File: types.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_optional_fields(cls) -> List[str]:
    """ return list of optional annotated fields """
    ret: List[str] = []
    for f in fields(cls):
        # Check if exactly two arguments exists and one of them are None type
        if hasattr(f.type, "__args__") and type(None) in f.type.__args__:
            ret.append(f.name)
    return ret 
Example #19
Source File: types.py    From ReAgent with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_dict(cls, d):
        return cls(**{f.name: d.get(f.name, None) for f in dataclasses.fields(cls)}) 
Example #20
Source File: test_dataclasses.py    From dacite with MIT License 5 votes vote down vote up
def test_get_default_value_for_field_without_default_value():
    @dataclass
    class X:
        i: int

    with pytest.raises(DefaultValueNotFoundError):
        get_default_value_for_field(field=fields(X)[0]) 
Example #21
Source File: echoes_user_preferences.py    From randovania with GNU General Public License v3.0 5 votes vote down vote up
def as_json(self) -> dict:
        result = {
            field.name: getattr(self, field.name)
            for field in dataclasses.fields(self)
        }
        result["sound_mode"] = self.sound_mode.value
        return result 
Example #22
Source File: ammo_state.py    From randovania with GNU General Public License v3.0 5 votes vote down vote up
def from_json(cls, value: dict) -> "AmmoState":
        kwargs = {}

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

        return cls(**kwargs) 
Example #23
Source File: echoes_user_preferences.py    From randovania with GNU General Public License v3.0 5 votes vote down vote up
def __post_init__(self):
        for field in dataclasses.fields(self):
            value = getattr(self, field.name)
            if "min" in field.metadata and value < field.metadata["min"]:
                raise ValueError(f'Value {value} for field "{field.name}" is less than minimum {field.metadata["min"]}')
            if "max" in field.metadata and value > field.metadata["max"]:
                raise ValueError(f'Value {value} for field "{field.name}" is less than maximum {field.metadata["max"]}') 
Example #24
Source File: bitpacking.py    From randovania with GNU General Public License v3.0 5 votes vote down vote up
def bit_pack_encode(self, metadata) -> Iterator[Tuple[int, int]]:
        reference = metadata.get("reference")

        for field in dataclasses.fields(self):
            if not field.init:
                continue

            item = getattr(self, field.name)
            if reference is not None:
                is_different = item != getattr(reference, field.name)
                yield from encode_bool(is_different)
                if not is_different:
                    continue

            yield from _get_bit_pack_value_for(item).bit_pack_encode(field.metadata) 
Example #25
Source File: conftest.py    From randovania with GNU General Public License v3.0 5 votes vote down vote up
def mock_dataclass(self, obj) -> MagicMock:
        return MagicMock(spec=[field.name for field in dataclasses.fields(obj)]) 
Example #26
Source File: naming.py    From gapic-generator-python with Apache License 2.0 5 votes vote down vote up
def __bool__(self):
        """Return True if any of the fields are truthy, False otherwise."""
        return any(
            (getattr(self, i.name) for i in dataclasses.fields(self)),
        ) 
Example #27
Source File: env.py    From podenv with Apache License 2.0 5 votes vote down vote up
def __repr__(self) -> str:
        # Format object by removing null attribute
        activeFields: List[str] = []
        for f in fields(Env):
            if f.metadata \
               and not f.metadata.get('internal', False):
                value = str(self.__dict__[f.name])
                if value:
                    if '\n' in value:
                        value = f'"""{value}"""'
                    elif ' ' in value:
                        value = f'"{value}"'
                    activeFields.append(f"{f.name}={value}")
        return "Env(%s)" % ", ".join(activeFields) 
Example #28
Source File: preferences.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def __load_settings(self) -> None:
        """Load settings on UI."""
        for field in fields(self.prefer):  # type: Field
            widget = getattr(self, field.name)
            value = getattr(self.prefer, field.name)
            if type(widget) is QSpinBox or type(widget) is QDoubleSpinBox:
                widget.setValue(value)
            elif type(widget) is QLineEdit:
                widget.setText(value)
            elif type(widget) is QCheckBox:
                widget.setChecked(value)
            elif type(widget) is QComboBox:
                widget.setCurrentIndex(value) 
Example #29
Source File: main_base.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def reset(self) -> None:
        """Reset the user values."""
        for field_obj in fields(self):  # type: Field
            setattr(self, field_obj.name, field_obj.default) 
Example #30
Source File: main_base.py    From Pyslvs-UI with GNU Affero General Public License v3.0 5 votes vote down vote up
def diff(self, other: Optional[Preferences]) -> Iterator[str]:
        """Show the fields of differences.
        Pass None to iterate over all names.
        """
        for field_obj in fields(self):  # type: Field
            name: str = field_obj.name
            if other is None or getattr(self, name) != getattr(other, name):
                yield name