当前位置: 首页>>代码示例>>Python>>正文


Python dataclasses.field方法代码示例

本文整理汇总了Python中dataclasses.field方法的典型用法代码示例。如果您正苦于以下问题:Python dataclasses.field方法的具体用法?Python dataclasses.field怎么用?Python dataclasses.field使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在dataclasses的用法示例。


在下文中一共展示了dataclasses.field方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_validate

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def test_validate():
    @dataclass
    class Config:
        foo: Optional[float] = field(
            default=None,
            metadata={
                'validate': _optional(_chain(_of_type(int, float), _positive)),
            },
        )

        def __post_init__(self):
            _validate(self)

    assert Config().foo is None
    assert Config(foo=0.123).foo == 0.123
    assert Config(foo=42).foo == 42

    with pytest.raises(ValueError, match='"foo" should be positive'):
        assert Config(foo=0)

    with pytest.raises(TypeError, match='"foo" should be of type'):
        assert Config(foo='a') 
开发者ID:vmagamedov,项目名称:grpclib,代码行数:24,代码来源:test_config.py

示例2: test_change_default

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def test_change_default():
    # all params should be optional
    @dataclass
    class Config:
        foo: Optional[float] = field(
            default=cast(None, _DEFAULT),
            metadata={
                'validate': _optional(_chain(_of_type(int, float), _positive)),
                'test-default': 1234,
            },
        )

        def __post_init__(self):
            _validate(self)

    assert _with_defaults(Config(foo=1), 'test-default').foo == 1 
开发者ID:vmagamedov,项目名称:grpclib,代码行数:18,代码来源:test_config.py

示例3: field

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def field(
    description: str,
    *args,
    action=None,
    required: bool = False,
    labeled: bool = False,
    metadata: Optional[dict] = None,
    **kwargs,
):
    """
    Creates an instance of :py:func:`dataclasses.field`. The first argument,
    ``description`` is the description of the field, and will be set as the
    ``"description"`` key in the metadata ``dict``.
    """
    if not metadata:
        metadata = {}
    metadata["description"] = description
    metadata["required"] = required
    metadata["labeled"] = labeled
    metadata["action"] = action
    return dataclasses.field(*args, metadata=metadata, **kwargs) 
开发者ID:intel,项目名称:dffml,代码行数:23,代码来源:base.py

示例4: config

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [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

示例5: test_modifiers

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def test_modifiers() -> None:
    conf: Modifiers = OmegaConf.structured(Modifiers)
    # regular fields cannot take None
    with pytest.raises(ValidationError):
        conf.num = None  # type: ignore

    # but Optional fields can
    conf.optional_num = None
    assert conf.optional_num is None

    # Accessing a missing field will trigger MissingMandatoryValue exception
    with pytest.raises(MissingMandatoryValue):
        # noinspection PyStatementEffect
        conf.another_num

    # but you can access it once it's been assigned
    conf.another_num = 42
    assert conf.another_num == 42 
开发者ID:omry,项目名称:omegaconf,代码行数:20,代码来源:test_dataclass_example.py

示例6: constant_field

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [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

示例7: with_context

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def with_context(self, *, collisions: FrozenSet[str]) -> 'Field':
        """Return a derivative of this field with the provided context.

        This method is used to address naming collisions. The returned
        ``Field`` object aliases module names to avoid naming collisions
        in the file being written.
        """
        return dataclasses.replace(
            self,
            message=self.message.with_context(
                collisions=collisions,
                skip_fields=True,
            ) if self.message else None,
            enum=self.enum.with_context(collisions=collisions)
            if self.enum else None,
            meta=self.meta.with_context(collisions=collisions),
        ) 
开发者ID:googleapis,项目名称:gapic-generator-python,代码行数:19,代码来源:wrappers.py

示例8: recursive_field_types

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def recursive_field_types(self) -> Sequence[
        Union['MessageType', 'EnumType']
    ]:
        """Return all composite fields used in this proto's messages."""
        types: Set[Union['MessageType', 'EnumType']] = set()

        stack = [iter(self.fields.values())]
        while stack:
            fields_iter = stack.pop()
            for field in fields_iter:
                if field.message and field.type not in types:
                    stack.append(iter(field.message.fields.values()))
                if not field.is_primitive:
                    types.add(field.type)

        return tuple(types) 
开发者ID:googleapis,项目名称:gapic-generator-python,代码行数:18,代码来源:wrappers.py

示例9: field_headers

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def field_headers(self) -> Sequence[str]:
        """Return the field headers defined for this method."""
        http = self.options.Extensions[annotations_pb2.http]

        pattern = re.compile(r'\{([a-z][\w\d_.]+)=')

        potential_verbs = [
            http.get,
            http.put,
            http.post,
            http.delete,
            http.patch,
            http.custom.path,
        ]

        return next((tuple(pattern.findall(verb)) for verb in potential_verbs if verb), ()) 
开发者ID:googleapis,项目名称:gapic-generator-python,代码行数:18,代码来源:wrappers.py

示例10: paged_result_field

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def paged_result_field(self) -> Optional[Field]:
        """Return the response pagination field if the method is paginated."""
        # If the request field lacks any of the expected pagination fields,
        # then the method is not paginated.
        for page_field in ((self.input, int, 'page_size'),
                           (self.input, str, 'page_token'),
                           (self.output, str, 'next_page_token')):
            field = page_field[0].fields.get(page_field[2], None)
            if not field or field.type != page_field[1]:
                return None

        # Return the first repeated field.
        for field in self.output.fields.values():
            if field.repeated and field.message:
                return field

        # We found no repeated fields. Return None.
        return None 
开发者ID:googleapis,项目名称:gapic-generator-python,代码行数:20,代码来源:wrappers.py

示例11: message_factory

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def message_factory(exp: str,
                    repeated_iter=itertools.repeat(False),
                    enum: Optional[wrappers.EnumType] = None) -> DummyMessage:
    # This mimics the structure of MessageType in the wrappers module:
    # A MessageType has a map from field names to Fields,
    # and a Field has an (optional) MessageType.
    # The 'exp' parameter is a dotted attribute expression
    # used to describe the field and type hierarchy,
    # e.g. "mollusc.cephalopod.coleoid"
    toks = exp.split(".")
    messages = [DummyMessage({}, tok.upper() + "_TYPE") for tok in toks]
    if enum:
        messages[-1] = enum

    for base, field, attr_name, repeated_field in zip(
        messages, messages[1:], toks[1:], repeated_iter
    ):
        base.fields[attr_name] = (DummyField(message=field, repeated=repeated_field)
                                  if isinstance(field, DummyMessage)
                                  else DummyField(enum=field))

    return messages[0] 
开发者ID:googleapis,项目名称:gapic-generator-python,代码行数:24,代码来源:common_types.py

示例12: test_from_dict_with_wrong_type

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def test_from_dict_with_wrong_type():
    @dataclass
    class X:
        s: str
        i: int

    with pytest.raises(WrongTypeError) as exception_info:
        from_dict(X, {"s": "test", "i": "wrong"})

    assert (
        str(exception_info.value)
        == 'wrong value type for field "i" - should be "int" instead of value "wrong" of type "str"'
    )
    assert exception_info.value.field_path == "i"
    assert exception_info.value.field_type == int
    assert exception_info.value.value == "wrong" 
开发者ID:konradhalas,项目名称:dacite,代码行数:18,代码来源:test_base.py

示例13: __set_id__

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def __set_id__(cls, instance: t.Any, id_value: IdType = None) -> t.Any:
        """Implements technical details of setting an ID value to the field.""" 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:4,代码来源:entity.py

示例14: __init_subclass__

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        id_fields = [(k, v) for k, v in cls.__dict__.items() if isinstance(v, Id)]
        if not getattr(cls, '__id_field_name__', None):
            assert len(id_fields) == 1, (
                f"Exactly one ID field is required for any Entity class. Got: "
                f"{dict(id_fields) if id_fields else None}"
            )
            cls.__id_field_name__ = id_fields[0][0]
        return dataclasses.dataclass(cls, eq=False) 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:12,代码来源:entity.py

示例15: __get_id_field__

# 需要导入模块: import dataclasses [as 别名]
# 或者: from dataclasses import field [as 别名]
def __get_id_field__(cls) -> Id:
        """Returns the field assumed to be the identity descriptor."""
        return getattr(cls, cls.__id_field_name__) 
开发者ID:pcah,项目名称:python-clean-architecture,代码行数:5,代码来源:entity.py


注:本文中的dataclasses.field方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。