本文整理汇总了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})"
示例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
示例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
示例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
示例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)
示例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)
示例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)
示例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)
示例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)
示例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))
示例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)
示例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)
示例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)
示例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)
示例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