本文整理匯總了Python中dataclasses.Field方法的典型用法代碼示例。如果您正苦於以下問題:Python dataclasses.Field方法的具體用法?Python dataclasses.Field怎麽用?Python dataclasses.Field使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類dataclasses
的用法示例。
在下文中一共展示了dataclasses.Field方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: resolve_defaults
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def resolve_defaults(func):
"""
Use this decorator to resolve default field values in the constructor.
"""
func_params = list(signature(func).parameters.values())
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(args) > len(func_params):
raise ValueError(
f"There are {len(func_params)} parameters in total, "
f"but args is {len(args)} long. \n"
f"{args}"
)
# go through unprovided default kwargs
for p in func_params[len(args) :]:
# only resolve defaults for Fields
if isinstance(p.default, Field):
if p.name not in kwargs:
kwargs[p.name] = _resolve_default(p.default)
return func(*args, **kwargs)
return wrapper
示例2: _get_default
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _get_default(catch_all_field: Field) -> Any:
# access to the default factory currently causes
# a false-positive mypy error (16. Dec 2019):
# https://github.com/python/mypy/issues/6910
# noinspection PyProtectedMember
has_default = not isinstance(catch_all_field.default,
dataclasses._MISSING_TYPE)
# noinspection PyProtectedMember
has_default_factory = not isinstance(catch_all_field.default_factory,
# type: ignore
dataclasses._MISSING_TYPE)
default_value = _CatchAllUndefinedParameters._SentinelNoDefault
if has_default:
default_value = catch_all_field.default
elif has_default_factory:
# This might be unwanted if the default factory constructs
# something expensive,
# because we have to construct it again just for this test
default_value = catch_all_field.default_factory() # type: ignore
return default_value
示例3: _decoder
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _decoder(
# NOTE: mypy incorrectly thinks `Field` is a generic type
data: Dict[str, EncodedConfigTypes],
fields: Collection[Field], # type: ignore
) -> Iterable[Tuple[str, ConfigTypes]]:
# NOTE: this code is unwieldly but it satisfies `mypy`
for field in fields:
if field.type is Gwei:
yield field.name, Gwei(cast(int, data[field.name]))
elif field.type is Slot:
yield field.name, Slot(cast(int, data[field.name]))
elif field.type is Epoch:
yield field.name, Epoch(cast(int, data[field.name]))
elif field.type is Second:
yield field.name, Second(cast(int, data[field.name]))
elif field.type is bytes:
yield field.name, decode_hex(cast(str, data[field.name]))
else:
yield field.name, int(data[field.name])
示例4: _get_fields
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _get_fields(cls, base_fields=True) -> List[JsonSchemaField]:
def _get_fields_uncached():
dataclass_bases = [
klass for klass in cls.__bases__ if is_dataclass(klass) and issubclass(klass, JsonSchemaMixin)
]
base_fields_types = set()
for base in dataclass_bases:
base_fields_types |= {(f.name, f.type) for f in fields(base)}
mapped_fields = []
type_hints = get_type_hints(cls)
for f in fields(cls):
# Skip internal fields
if f.name.startswith("__") or (not base_fields and (f.name, f.type) in base_fields_types):
continue
# Note fields() doesn't resolve forward refs
f.type = type_hints[f.name]
mapped_fields.append(JsonSchemaField(f, cls.field_mapping().get(f.name, f.name)))
if cls.__serialise_properties:
include_properties = None
if isinstance(cls.__serialise_properties, tuple):
include_properties = set(cls.__serialise_properties)
members = inspect.getmembers(cls, inspect.isdatadescriptor)
for name, member in members:
if name != "__weakref__" and (include_properties is None or name in include_properties):
f = Field(MISSING, None, None, None, None, None, None)
f.name = name
f.type = member.fget.__annotations__['return']
mapped_fields.append(JsonSchemaField(f, name, is_property=True))
return mapped_fields
if not base_fields:
return _get_fields_uncached()
if not cls.__mapped_fields:
cls.__mapped_fields = _get_fields_uncached()
return cls.__mapped_fields # type: ignore
示例5: _get_field_meta
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _get_field_meta(cls, field: Field, schema_type: SchemaType) -> Tuple[FieldMeta, bool]:
required = True
field_meta = FieldMeta(schema_type=schema_type)
default_value = MISSING
if field.default is not MISSING:
# In case of default value given
default_value = field.default
elif field.default_factory is not MISSING and field.default_factory is not None: # type: ignore
# In case of a default factory given, we call it
default_value = field.default_factory() # type: ignore
if default_value is not MISSING:
field_meta.default = cls._encode_field(field.type, default_value, omit_none=False)
required = False
if field.metadata is not None:
if "examples" in field.metadata:
field_meta.examples = [
cls._encode_field(field.type, example, omit_none=False) for example in field.metadata["examples"]
]
if "extensions" in field.metadata:
field_meta.extensions = field.metadata["extensions"]
if "description" in field.metadata:
field_meta.description = field.metadata["description"]
if "title" in field.metadata:
field_meta.title = field.metadata["title"]
if schema_type == SchemaType.OPENAPI_3:
field_meta.read_only = field.metadata.get("read_only")
if field_meta.read_only and default_value is MISSING:
warnings.warn(f"Read-only fields should have a default value")
field_meta.write_only = field.metadata.get("write_only")
return field_meta, required
示例6: from_json_dict
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def from_json_dict(cls, json_dict: dict) -> "PatcherConfiguration":
kwargs = {}
for field in dataclasses.fields(cls):
field: dataclasses.Field = field
if field.name in json_dict:
kwargs[field.name] = field.type(json_dict[field.name])
return PatcherConfiguration(**kwargs)
示例7: _resolve_default
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _resolve_default(val):
if not isinstance(val, Field):
return val
if val.default != MISSING:
return val.default
if val.default_factory != MISSING:
return val.default_factory()
raise ValueError("No default value")
示例8: _proxied_class_schema
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _proxied_class_schema(
clazz: type, base_schema: Optional[Type[marshmallow.Schema]] = None
) -> Type[marshmallow.Schema]:
try:
# noinspection PyDataclass
fields: Tuple[dataclasses.Field, ...] = dataclasses.fields(clazz)
except TypeError: # Not a dataclass
try:
return class_schema(dataclasses.dataclass(clazz), base_schema)
except Exception:
raise TypeError(
f"{getattr(clazz, '__name__', repr(clazz))} is not a dataclass and cannot be turned into one."
)
# Copy all marshmallow hooks and whitelisted members of the dataclass to the schema.
attributes = {
k: v
for k, v in inspect.getmembers(clazz)
if hasattr(v, "__marshmallow_hook__") or k in MEMBERS_WHITELIST
}
# Update the schema members to contain marshmallow fields instead of dataclass fields
attributes.update(
(
field.name,
field_for_schema(
field.type, _get_field_default(field), field.metadata, base_schema
),
)
for field in fields
if field.init
)
schema_class = type(clazz.__name__, (_base_schema(clazz, base_schema),), attributes)
return cast(Type[marshmallow.Schema], schema_class)
示例9: _field_by_type
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _field_by_type(
typ: Union[type, Any], base_schema: Optional[Type[marshmallow.Schema]]
) -> Optional[Type[marshmallow.fields.Field]]:
return (
base_schema and base_schema.TYPE_MAPPING.get(typ)
) or marshmallow.Schema.TYPE_MAPPING.get(typ)
示例10: _get_field_default
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _get_field_default(field: dataclasses.Field):
"""
Return a marshmallow default value given a dataclass default value
>>> _get_field_default(dataclasses.field())
<marshmallow.missing>
"""
# Remove `type: ignore` when https://github.com/python/mypy/issues/6910 is fixed
default_factory = field.default_factory # type: ignore
if default_factory is not dataclasses.MISSING:
return default_factory
elif field.default is dataclasses.MISSING:
return marshmallow.missing
return field.default
示例11: _get_catch_all_field
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def _get_catch_all_field(cls) -> Field:
catch_all_fields = list(
filter(lambda f: f.type == Optional[CatchAllVar], fields(cls)))
number_of_catch_all_fields = len(catch_all_fields)
if number_of_catch_all_fields == 0:
raise UndefinedParameterError(
"No field of type dataclasses_json.CatchAll defined")
elif number_of_catch_all_fields > 1:
raise UndefinedParameterError(
f"Multiple catch-all fields supplied: "
f"{number_of_catch_all_fields}.")
else:
return catch_all_fields[0]
示例12: NewType
# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import Field [as 別名]
def NewType(
name: str,
typ: Type[_U],
field: Optional[Type[marshmallow.fields.Field]] = None,
**kwargs,
) -> Callable[[_U], _U]:
"""NewType creates simple unique types
to which you can attach custom marshmallow attributes.
All the keyword arguments passed to this function will be transmitted
to the marshmallow field constructor.
>>> import marshmallow.validate
>>> IPv4 = NewType('IPv4', str, validate=marshmallow.validate.Regexp(r'^([0-9]{1,3}\\.){3}[0-9]{1,3}$'))
>>> @dataclass
... class MyIps:
... ips: List[IPv4]
>>> MyIps.Schema().load({"ips": ["0.0.0.0", "grumble grumble"]})
Traceback (most recent call last):
...
marshmallow.exceptions.ValidationError: {'ips': {1: ['String does not match expected pattern.']}}
>>> MyIps.Schema().load({"ips": ["127.0.0.1"]})
MyIps(ips=['127.0.0.1'])
>>> Email = NewType('Email', str, field=marshmallow.fields.Email)
>>> @dataclass
... class ContactInfo:
... mail: Email = dataclasses.field(default="anonymous@example.org")
>>> ContactInfo.Schema().load({})
ContactInfo(mail='anonymous@example.org')
>>> ContactInfo.Schema().load({"mail": "grumble grumble"})
Traceback (most recent call last):
...
marshmallow.exceptions.ValidationError: {'mail': ['Not a valid email address.']}
"""
def new_type(x: _U):
return x
new_type.__name__ = name
new_type.__supertype__ = typ # type: ignore
new_type._marshmallow_field = field # type: ignore
new_type._marshmallow_args = kwargs # type: ignore
return new_type