本文整理匯總了Python中dataclasses.dataclass方法的典型用法代碼示例。如果您正苦於以下問題:Python dataclasses.dataclass方法的具體用法?Python dataclasses.dataclass怎麽用?Python dataclasses.dataclass使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類dataclasses
的用法示例。
在下文中一共展示了dataclasses.dataclass方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def __init__(self, config_class, time, **kwargs):
"""Specify an intervention in the dynamical system.
Parameters
----------
time: int
Time of the intervention.
config_class:
The Config class, a child class of dataclass.
kwargs: dict
Only valid keyword arguments are parameters of the config class.
"""
self.time = time
config_args = set(f.name for f in dataclasses.fields(config_class))
for arg in kwargs:
if arg not in config_args:
raise TypeError(f"__init__() got an unexpected keyword argument {arg}!")
self.updates = kwargs
示例2: test_baseconfig
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def test_baseconfig():
"""Test the basic configuration object."""
@dataclasses.dataclass
class Config(wn.dynamics.BaseConfig):
param1: float = 0
param2: float = 23
config = Config()
assert config.parameter_names() == ["param1", "param2"]
intervention = wn.dynamics.BaseIntervention(Config, 1970, param1=19)
assert config.param1 == 0
updated = config.update(intervention)
assert config.param1 == 0
assert config.param2 == 23
assert updated.param1 == 19
assert updated.param2 == 23
示例3: test_basestate
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def test_basestate():
"""Test the basic state object."""
@dataclasses.dataclass
class State(wn.dynamics.BaseState):
state1: float = 0
state2: float = 1
state3: float = 3
assert State.num_variables() == 3
assert State.variable_names() == ["state1", "state2", "state3"]
state2 = [2]
state = State(state2=state2)
assert state.num_variables() == 3
values = state.values()
assert values[0] == 0
assert values[1] == [2]
assert values[2] == 3
# Ensure values are shallow copied
assert values[1] is state2
示例4: to_dict
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def to_dict(self, omit_none: bool = True, validate: bool = False, validate_enums: bool = True) -> JsonDict:
"""Converts the dataclass instance to a JSON encodable dict, with optional JSON schema validation.
If omit_none (default True) is specified, any items with value None are removed
"""
data = {}
for f in self._get_fields():
value = getattr(self, f.field.name)
try:
value = self._encode_field(f.field.type, value, omit_none)
except UnknownEnumValueError as e:
warnings.warn(str(e))
if omit_none and value is None:
continue
if value is NULL:
value = None
data[f.mapped_name] = value
if self.__discriminator_name is not None:
data[self.__discriminator_name] = self.__class__.__name__
if validate:
self._validate(data, validate_enums)
return data
示例5: test_variablesize
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def test_variablesize(self):
@dataclass(frozen=True)
@streamable
class TestClass2(Streamable):
a: uint32
b: uint32
c: bytes
a = TestClass2(uint32(1), uint32(2), b"3")
bytes(a)
@dataclass(frozen=True)
@streamable
class TestClass3(Streamable):
a: int
b = TestClass3(1)
try:
bytes(b)
assert False
except NotImplementedError:
pass
示例6: test_recursive_json
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def test_recursive_json(self):
@dataclass(frozen=True)
@streamable
class TestClass1(Streamable):
a: List[uint32]
@dataclass(frozen=True)
@streamable
class TestClass2(Streamable):
a: uint32
b: List[Optional[List[TestClass1]]]
c: bytes32
tc1_a = TestClass1([uint32(1), uint32(2)])
tc1_b = TestClass1([uint32(4), uint32(5)])
tc1_c = TestClass1([uint32(7), uint32(8)])
tc2 = TestClass2(
uint32(5), [[tc1_a], [tc1_b, tc1_c], None], bytes32(bytes([1] * 32))
)
assert TestClass2.from_json_dict(tc2.to_json_dict()) == tc2
示例7: __init__
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [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)
示例8: __set_fields
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [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)
示例9: test_validate_works_with_dataclasses
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def test_validate_works_with_dataclasses(self):
"""
Test we can compile @dataclass
@dataclass inspects `sys.modules`, so the module needs to be in
`sys.modules` when @dataclass is run.
"""
mod = _compile(
"foo",
textwrap.dedent(
"""
from __future__ import annotations
from dataclasses import dataclass
def render(table, params):
return table
@dataclass
class A:
y: int
"""
).encode("utf-8"),
)
self.kernel.validate(mod) # do not raise
示例10: __init_subclass__
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def __init_subclass__(cls, **kwargs):
return dataclasses.dataclass(cls, init=True, frozen=True, repr=False)
示例11: __set_name__
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def __set_name__(self, owner, name):
super().__set_name__(owner, name)
annotations = {
name: owner.__annotations__.get(name, None)
for name in self._field_names
}
assert all(annotations.values()), (
f"Entity owner has to have all field_names as dataclass "
f"annotations: {self._field_names}"
)
# TODO assert immutability of the fields
示例12: __init_subclass__
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [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)
示例13: __init__
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def __init__(self, **kwargs):
"""
This initializer will be overridden by dataclass decorator above. It is needed to
persuade static type checkers that Entities have initializers.
"""
示例14: _monkeypatch_to_fix_certificate_asdict
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def _monkeypatch_to_fix_certificate_asdict() -> None:
# H4ck: monkeypatch the _Certificate class to add __deepcopy__() so that when we call asdict() on a dataclass
# that contains a _Certificate, asdict() succeeds. Without this, generating JSON for the certinfo scan command
# will crash because the asdict() function uses deepcopy(), but certificates returned by cryptography.x509
# don't support it so SSLyze would crash. This class is a workaround to fix JSON output.
# I opened an issue about it in the cryptography repo at https://github.com/pyca/cryptography/issues/5129
def _deepcopy_method_for_x509_certificate(inner_self: _Certificate, memo: str) -> x509.Certificate:
return x509.load_pem_x509_certificate(inner_self.public_bytes(Encoding.PEM), backend=default_backend())
_Certificate.__deepcopy__ = _deepcopy_method_for_x509_certificate
# Call it on import... hacky but we don't have a choice
示例15: test_long_repr
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import dataclass [as 別名]
def test_long_repr(self):
@dataclass(repr=False)
class LongContainer(Model):
attribute_1: int = 1
attribute_2: int = 2
attribute_3: int = 3
attribute_4: int = 4
attribute_5: int = 5
@dataclass(repr=False)
class LongData(Model):
data: LongContainer
data_list: List[LongContainer]
builtin_list: List[int]
raw_dict: dict
string: str
boolean: bool
data = LongData(
LongContainer(),
[LongContainer() for _ in range(20)],
list(range(10)),
{str(k): k for k in range(20)},
'really long string which will most probably be cut off' * 2,
True
)
repr(data)