當前位置: 首頁>>代碼示例>>Python>>正文


Python dataclasses.fields方法代碼示例

本文整理匯總了Python中dataclasses.fields方法的典型用法代碼示例。如果您正苦於以下問題:Python dataclasses.fields方法的具體用法?Python dataclasses.fields怎麽用?Python dataclasses.fields使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在dataclasses的用法示例。


在下文中一共展示了dataclasses.fields方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __repr__

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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})" 
開發者ID:pcah,項目名稱:python-clean-architecture,代碼行數:18,代碼來源:value_object.py

示例2: add_slots

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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 
開發者ID:ericvsmith,項目名稱:dataclasses,代碼行數:26,代碼來源:dataclass_tools.py

示例3: to_json_value

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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 
開發者ID:edgedb,項目名稱:edgedb,代碼行數:19,代碼來源:types.py

示例4: from_json

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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 
開發者ID:Enforcer,項目名稱:clean-architecture,代碼行數:18,代碼來源:serializing.py

示例5: to_json

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:Enforcer,項目名稱:clean-architecture,代碼行數:18,代碼來源:serializing.py

示例6: config

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:intel,項目名稱:dffml,代碼行數:27,代碼來源:base.py

示例7: __init__

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:intel,項目名稱:dffml,代碼行數:24,代碼來源:cmd.py

示例8: restore_settings

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:KmolYuan,項目名稱:Pyslvs-UI,代碼行數:24,代碼來源:io.py

示例9: constant_field

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:stanfordnqp,項目名稱:spins-b,代碼行數:18,代碼來源:flows.py

示例10: writeReferences

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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)) 
開發者ID:podenv,項目名稱:podenv,代碼行數:25,代碼來源:generate.py

示例11: bit_pack_unpack

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:randovania,項目名稱:randovania,代碼行數:22,代碼來源:bitpacking.py

示例12: __init__

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:GoogleCloudPlatform,項目名稱:professional-services,代碼行數:21,代碼來源:report.py

示例13: __set_fields

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:GoogleCloudPlatform,項目名稱:professional-services,代碼行數:18,代碼來源:report.py

示例14: add_transition

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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) 
開發者ID:facebookresearch,項目名稱:ReAgent,代碼行數:19,代碼來源:types.py

示例15: _contains_non_default_init_vars

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import fields [as 別名]
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 
開發者ID:abatilo,項目名稱:typed-json-dataclass,代碼行數:26,代碼來源:typed_json_dataclass.py


注:本文中的dataclasses.fields方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。