API Docs¶
Structs¶
- class structtype.Struct¶
A base class for defining efficient serializable objects.
Fields are defined using type annotations. Fields may optionally have default values, which result in keyword parameters to the constructor.
Structs automatically define
__init__,__eq__,__repr__, and__copy__methods. Additional methods can be defined on the class as needed. Note that__init__/__new__cannot be overridden, but other methods can. A tuple of the field names is available on the class via the__struct_fields__attribute if needed.Additional class options can be set via a
struct_configclass attribute using aStructConfigdict (see example below). These configuration options may also be inspected at runtime through the__struct_config__attribute. The sparsestruct_configattribute itself is always present and defaults to{}when never declared.- Configuration:
frozen (bool, default False) – Whether instances of this type are pseudo-immutable. If true, attribute assignment is disabled and a corresponding
__hash__is defined.order (bool, default False) – If True,
__lt__,__le__`,__gt__, and__ge__methods will be generated for this type.eq (bool, default True) – If True (the default), an
__eq__method will be generated for this type. Set to False to compare based on instance identity alone.kw_only (bool, default False) – If True, all fields will be treated as keyword-only arguments in the generated
__init__method. Default is False.omit_defaults (bool, default False) – Whether fields should be omitted from encoding if the corresponding value is the default for that field. Enabling this may reduce message size, and often also improve encoding & decoding performance.
forbid_unknown_fields (bool, default False) – If True, an error is raised if an unknown field is encountered while decoding structs of this type. If False (the default), no error is raised and the unknown field is skipped.
tag (str, int, bool, callable, or None, default None) – Used along with
tag_fieldfor configuring tagged union support. If either are non-None, then the struct is considered “tagged”. In this case, an extra field (thetag_field) and value (thetag) are added to the encoded message, which can be used to differentiate message types during decoding.Set
tag=Trueto enable the default tagged configuration (tag_fieldis"type",tagis the class name). Alternatively, you can provide a string (or less commonly int) value directly to be used as the tag (e.g.tag="my-tag-value").``tag`` can also be passed a callable that takes the class qualname and returns a valid tag value (e.g.tag=str.lower). See the docs for more information.tag_field (str or None, default None) – The field name to use for tagged union support. If
tagis non-None, then this defaults to"type". See thetagdocs above for more information.rename (str, mapping, callable, or None, default None) – Controls renaming the field names used when encoding/decoding the struct. May be one of
"lower","upper","camel","pascal", or"kebab"to rename in lowercase, UPPERCASE, camelCase, PascalCase, or kebab-case respectively. May also be a mapping from field names to the renamed names (missing fields are not renamed). Alternatively, may be a callable that takes the field name and returns a new name orNoneto not rename that field. Default isNonefor no field renaming.repr_omit_defaults (bool, default False) – Whether fields should be omitted from the generated repr if the corresponding value is the default for that field.
array_like (bool, default False) – If True, this struct type will be treated as an array-like type during encoding/decoding, rather than a dict-like type (the default). This may improve performance, at the cost of a more inscrutable message encoding.
weakref (bool, default False) – Whether instances of this type support weak references. Defaults to False.
dict (bool, default False) – Whether instances of this type will include a
__dict__. Setting this to True will allow adding additional undeclared attributes to a struct instance, which may be useful for holding private runtime state. Defaults to False.cache_hash (bool, default False) – If enabled, the hash of a frozen struct instance will be computed at most once, and then cached on the instance for further reuse. For expensive hash values this can improve performance at the cost of a small amount of memory usage.
check_types_on_init (bool, default False) – If True, the generated
__init__validates the field values against their declared types and constraints when an instance is created, raising aValidationErrorif any value does not match. Default is False.
Examples
Here we define a new
Structtype for describing a dog. It has three fields; two required and one optional.>>> class Dog(Struct): ... name: str ... breed: str ... is_good_boy: bool = True ... >>> Dog('snickers', breed='corgi') Dog(name='snickers', breed='corgi', is_good_boy=True)
Additional struct options can be set via a
struct_configclass attribute. Here we define a newStructtype for a frozenPointobject.>>> class Point(Struct): ... struct_config = StructConfig(frozen=True) ... x: float ... y: float ... >>> {Point(1.5, 2.0): 1} # frozen structs are hashable {Point(x=1.5, y=2.0): 1}
- __struct_fields__¶
-
A tuple of the field names in declaration order. Available on both the struct type and on instances.
- __struct_alias_fields__¶
-
A tuple of the field names used for serialization, in declaration order. These are the field names after applying any
renameconfiguration. Available on both the struct type and on instances.
- __struct_defaults__¶
- Type:
tuple[Any, …]
A tuple of the default values for each field, in declaration order. Fields without a default use
NODEFAULT. Available on both the struct type and on instances.
- __struct_config__¶
- Type:
The
StructConfigfor this struct type. Available on both the struct type and on instances.
- struct_config¶
- Type:
The
StructConfigdict as declared in the class body (sparse — only the keys the user explicitly set). Always present: defaults to{}when no class in the hierarchy declares one. Available on both the struct type and on instances. Use__struct_config__for the fully-resolved configuration.
- __match_args__¶
-
A tuple of the field names used for positional pattern matching. Available on the struct type.
- __signature__¶
- Type:
The computed
__init__signature for the struct type. Available on the struct type.
- __slots__¶
-
The field names stored as instance slots. On the base
Structclass this is empty; subclasses get one slot per field.
- __iter__()¶
Iterate over the struct as
(name, value)pairs in declaration order. This enablesdict(p),list(p), anditer(p)support.
- __copy__()¶
Return a shallow copy of the struct, enabling
copy.copy(p).
- __replace__(**changes)¶
Create a new struct with the given fields replaced, enabling
copy.replace(p, ...).
- __reduce__()¶
Return state information for pickling, enabling
pickle.dumpandcopy.deepcopysupport.
- __rich_repr__()¶
Return a list of
(name, value)pairs used by IPython and Jupyter for a structured display of the struct.
Note
A field name may shadow any of these methods or attributes (for example a field called
struct_dump). Shadowing is allowed, but the field’s slot then takes precedence, so the member is no longer reachable on instances. Struct creation emits aUserWarningwhen a new field’s name starts withstruct_and matches a known struct member (thestruct_*methods above orstruct_config). Astruct_-prefixed name that matches no known member, and shadowing of anything else (parent methods, dunders), is silent — as in plain Python. Re-declaring a parent’s field is normal overriding and stays silent too. Usewarnings.filterwarnings("error", ...)to turn the warning into a hard error.- struct_check_types()¶
Check this struct’s field values against their declared types and constraints.
This is a pure type-check: unlike
struct_validate, no conversion is performed. Raises aValidationErrorif any field’s value does not match its declared type. If the value is not already an instance of the declared custom type, the error is raised immediately (Serializer.loadand protocol fallbacks are skipped). Any annotatedConstraintis still called on correctly-typed values.If
check_types_on_init=Truewas set on the struct class, this check is also performed at construction time.
- struct_dump(*, sort_keys=False, str_keys=False, builtin_types=None)¶
Convert this struct to built-in Python types compatible with JSON basic types.
This applies the same semantics as
struct_dump_jsonbut produces Python objects instead of JSON bytes:Struct-level settings are honored:
rename,omit_defaults,array_like, andtagfor tagged unions.Fields containing
UNSETare omitted from the output.Nested structs, dataclasses, attrs, TypedDict, and NamedTuple values are recursively expanded.
Types without a direct builtin equivalent are converted to their serializable representations.
- Parameters:
sort_keys (bool, optional) – If
True, dict keys and set elements are sorted so that equal values produce identical output. Struct, dataclass, and object fields keep their declaration order. Default isFalse.str_keys (bool, optional) – Whether to convert all object keys to strings. Default is
False.builtin_types (Iterable[type], optional) – An iterable of types to treat as additional builtin types. These types will be passed through unchanged. Currently supports
bytes,bytearray,memoryview,datetime.datetime,datetime.time,datetime.date,datetime.timedelta,uuid.UUID,decimal.Decimal,enum.Enum, and custom types. UseALL_BUILTIN_TYPESas a shortcut to pass through all supported types.
- Returns:
dict or list – The converted object. For
array_like=Falsestructs returns adict. Forarray_like=Truestructs returns alist.
- struct_dump_csv()¶
Return this Struct as a single CSV row: a list of cell strings in field declaration order, ready to pass to csv.writer.writerow(). None -> empty, bools -> true/false, bytes -> base64. The caller owns the delimiter, quoting, dialect, encoding, and stream.
- struct_dump_json(*, decimal_as_number=False, uuid_as_hex=False, sort_keys=False)¶
Serialize this struct to JSON bytes.
- Parameters:
decimal_as_number (bool, optional) – Controls how
decimal.Decimalvalues are encoded. IfFalse(default), encodes as JSON strings. IfTrue, encodes as JSON numbers (may lose precision when decoded by some libraries).uuid_as_hex (bool, optional) – Controls how
uuid.UUIDvalues are encoded. IfFalse(default), encodes in canonical form (xxxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx). IfTrue, encodes as hex (xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx) .sort_keys (bool, optional) – If
True, dict keys and set elements are sorted so that equal values produce identical output. Struct, dataclass, and object fields keep their declaration order. Default isFalse.
- Returns:
data (bytes) – The serialized JSON.
- classmethod struct_validate(cls, obj, *, strict=True, from_attributes=False)¶
Convert built-in types to an instance of this struct type.
- Parameters:
obj (Any) – The object to convert.
strict (bool, optional) – Whether type coercion rules should be strict. If
False, enables a wider set of coercion rules from string to non-string types for all values, including dict keys. Default isTrue.from_attributes (bool, optional) – If
True, input objects may be coerced to struct, dataclass, or attrs types by extracting attributes matching output field names. Default isFalse.
- Returns:
Self – A validated struct instance.
- classmethod struct_validate_csv(cls, row, *, null_values=('',))¶
Decode a single CSV row (a sequence of cell strings) into a Struct instance. Cells are matched positionally to fields in declaration order and coerced with lax string rules. Cells listed in
null_valuesbecome None. The caller owns the delimiter, quoting, dialect, encoding, and stream.
- classmethod struct_validate_json(cls, buf, *, strict=True)¶
Deserialize JSON bytes to an instance of this struct type.
- class structtype.StructMeta(name, bases, namespace, /)¶
The metaclass for creating
Structtypes. See its documentation for the available configuration options when subclassing.Struct configuration is provided via a
struct_configclass attribute in the class body, using aStructConfigdict.For project-wide config defaults, prefer a base
Structclass with astruct_configattribute — no custom metaclass is needed.StructMeta can be subclassed, and may be combined with
abc.ABCMetato define abstract base Structs. Other metaclass combinations are not supported; they may work by accident but are not considered part of the public API.Examples
Set a project-wide config default by defining a base class:
>>> from structtype import Struct, StructConfig >>> class KwOnlyStruct(Struct): ... struct_config = StructConfig(kw_only=True) ... >>> class Example(KwOnlyStruct): ... a: str = "" ... b: int ... >>> Example(b=123) Example(a='', b=123)
Class-statement kwargs pass through to
__init_subclass__, but do not affect struct configuration — set config only via thestruct_configclass attribute.
- structtype.fields(type_or_instance)¶
Get introspection information about a struct’s fields.
Returns a tuple of
FieldInfoobjects describing each field in declaration order.- Parameters:
type_or_instance (Struct or type[Struct]) – A struct type or struct instance.
- Returns:
tuple[FieldInfo, …] – A tuple of FieldInfo objects, one per field in declaration order.
Examples
>>> from structtype import Struct, fields
>>> class Point(Struct): ... x: float ... y: float
>>> fields(Point) (FieldInfo(name='x', alias='x', type=<class 'float'>, required=True), FieldInfo(name='y', alias='y', type=<class 'float'>, required=True))
- structtype.json_schema(type, *, schema_hook=None, ref_template='#/$defs/{name}')¶
Generate a JSON Schema for a given type.
Any schemas for (potentially) shared components are extracted and stored in a top-level
"$defs"field.If you want to generate schemas for multiple types, or to have more control over the generated schema you may want to use
json_schema_componentsinstead.- Parameters:
type (type) – The type to generate the schema for.
schema_hook (callable, optional) – An optional callback to use for generating JSON schemas of custom types. Will be called with the custom type, and should return a dict representation of the JSON schema for that type.
ref_template (str, optional) – A template to use when generating
"$ref"fields. This template is formatted with the type name astemplate.format(name=name). This can be useful if you intend to store thecomponentsmapping somewhere other than a top-level"$defs"field. For example, you might useref_template="#/components/{name}"if generating an OpenAPI schema.
- Returns:
schema (dict) – The generated JSON Schema.
See also
- structtype.json_schema_dump(type, *, schema_hook=None, ref_template='#/$defs/{name}')¶
Generate a JSON Schema for the given type, returned as JSON bytes.
This is a convenience wrapper around
json_schema()that encodes the result to JSON.
- structtype.json_schema_components(types, *, schema_hook=None, ref_template='#/$defs/{name}')¶
Generate JSON Schemas for one or more types.
Any schemas for (potentially) shared components are extracted and returned in a separate
componentsdict.- Parameters:
types (Iterable[type]) – An iterable of one or more types to generate schemas for.
schema_hook (callable, optional) – An optional callback to use for generating JSON schemas of custom types. Will be called with the custom type, and should return a dict representation of the JSON schema for that type.
ref_template (str, optional) – A template to use when generating
"$ref"fields. This template is formatted with the type name astemplate.format(name=name). This can be useful if you intend to store thecomponentsmapping somewhere other than a top-level"$defs"field. For example, you might useref_template="#/components/{name}"if generating an OpenAPI schema.
- Returns:
schemas (tuple[dict]) – A tuple of JSON Schemas, one for each type in
types.components (dict) – A mapping of name to schema for any shared components used by
schemas.
See also
schema
- class structtype.FieldInfo(name, alias, type, default=<object object>, default_factory=<object object>)¶
An introspection record for a single struct field.
Obtain instances via
fields(), which returns oneFieldInfoper field in declaration order.Examples
>>> class Point(Struct): ... x: float ... y: float
>>> for info in fields(Point): ... print(info) FieldInfo(name='x', alias='x', type=<class 'float'>, required=True) FieldInfo(name='y', alias='y', type=<class 'float'>, required=True)
Note
FieldInfois the read side of field metadata — you obtain it by callingstructtype.fields(). To set metadata (aliases, descriptions, JSON schema extra, …) on a field, usetyping.AnnotatedwithFieldin the annotation — see Field Annotations.- name¶
The Python field name (the name used in
__init__and as a dict key).
- alias¶
The name used for serialization — equals name unless
Field(alias=...)orStructConfig(rename=...)is used.
- type¶
The field’s type annotation.
- default¶
The default value, or
NODEFAULTfor required fields.
- default_factory¶
A callable that produces the default value, or
NODEFAULTif none.
Example:
>>> from structtype import Struct, fields, Factory >>> class User(Struct): ... name: str ... age: int = 0 >>> for info in fields(User): ... print(f"{info.name}: required={info.required}") name: required=True age: required=False
- property required¶
True when the field has no default and no default factory.
- class structtype.StructConfig¶
Configuration for a Struct type, mirroring the Struct config options.
Used as a class-body
struct_configattribute. Keys not present inherit from the base class;__struct_config__returns the fully-resolved dict.struct_configreturns exactly what the user wrote (sparse dict), and is always present — it defaults to{}when never declared.A
typing.TypedDictwithtotal=Falsecontaining 15 optional keys.StructConfig(frozen=True)returns a plaindictat runtime.Important
isinstance(x, StructConfig)raisesTypeErroron all Python versions. Useisinstance(x, dict)instead, or access individual keys directly.Keys:
- frozen¶
- Type:
Make instances immutable —
setattr/delattrraiseFrozenInstanceError. Enables__hash__(only wheneq=True, the default). See Frozen Instances.
- order¶
- Type:
Generate
__lt__,__le__,__gt__,__ge__. Requireseq=True. See Equality and Order.
- repr_omit_defaults¶
- Type:
Omit fields equal to their default value in
__repr__. Described in Configuration Inheritance.
- array_like¶
- Type:
Encode as positional array (
list/tuple) instead of a JSON object. Described in Supported Types.
- weakref¶
- Type:
Allow
weakref.refon instances (one pointer per instance). Described in Configuration Inheritance.
- dict¶
- Type:
Give instances a
__dict__for arbitrary runtime attributes. Described in Configuration Inheritance.
- cache_hash¶
- Type:
Cache the hash of frozen struct instances after the first
hash()call. Described in Configuration Inheritance.
- omit_defaults¶
- Type:
Omit fields equal to their default value in
struct_dump_jsonoutput. See Omitting Default Values.
- forbid_unknown_fields¶
- Type:
Raise
ValidationErroron unknown keys instruct_validate/struct_validate_json. See Forbidding Unknown Fields.
- check_types_on_init¶
- Type:
Run type and constraint validation on every
__init__call. See check_types_on_init.
- tag¶
-
The discriminant value used for tagged unions — either a fixed value or a callable that maps the class name to one. Set to
Falseto explicitly disable tagging. See Tagged Unions.
- tag_field¶
- Type:
str | None
The key used to store the discriminant value. Defaults to
"type"when either tag or tag_field is set. See Tagged Unions.
- rename¶
- Type:
None | Literal[“lower”, “upper”, “camel”, “pascal”, “kebab”] | Callable[[str], str | None] | Mapping[str, str]
Rename fields for serialization. Accepts a preset string (
"lower","upper","camel","pascal","kebab"), a callable(name) -> new_name | None, or a dict mapping original names to serialized names. See Renaming Fields.
- structtype.NODEFAULT¶
A singleton indicating no default value is configured.
Field¶
- class structtype.Field¶
Configuration for a Struct field identity and json-schema metadata.
- Parameters:
alias (str, optional) – An alternative name to use when encoding/decoding this field. If present, this will override any struct-level configuration using the
renameoption for this field.title (str, optional) – The title to use for the annotated value when generating a json-schema.
description (str, optional) – The description to use for the annotated value when generating a json-schema.
examples (list, optional) – A list of examples to use when generating a json-schema.
deprecated (bool, optional) – Mark the annotated value as deprecated in the generated json-schema.
json_schema_extra (dict, optional) – A dict of extra fields to set when generating a json-schema. This dict is recursively merged with the generated schema, with
json_schema_extraoverriding any conflicting autogenerated fields.
Examples
>>> from typing import Annotated >>> from structtype import Struct, Field >>> class User(Struct): ... name: Annotated[str, Field(alias="user_name")] ... >>> User.struct_validate_json(b'{"user_name": "alice"}') User(name='alice')
- alias¶
An alternative name to use when encoding/decoding this field
Factory¶
- class structtype.Factory¶
A wrapper around a zero-argument callable used as a dynamic default value.
A default value may be a plain value, which is shared by every instance, or a
Factory, whose wrapped callable is invoked with no arguments to create a fresh default for each instance. Wrapping the callable makes it explicit that it produces the default value rather than being the default value itself, which is otherwise ambiguous.This is useful for mutable defaults that should not be shared between instances, and for defaults that depend on runtime state (e.g.
Factory(uuid.uuid4)). Builtin empty mutable collections ([],{},set(), andbytearray()) used as defaults are shorthand forFactory(list),Factory(dict), and friends. The wrapped callable is exposed as the read-onlyfactoryattribute.- factory¶
The factory function
Serializer¶
- class structtype.Serializer¶
Configuration for converting values to/from a custom type.
- Parameters:
load (callable, optional) – A callable converting an incoming serializable value to an instance of the annotated custom type during decoding/validation.
dump (callable, optional) – A callable converting an instance of the annotated custom type to a serializable value during encoding.
None (Both parameters default to)
is (indicating no conversion)
direction. (performed in that)
- dump
- Type:
Callable[[Any], Any] | None
A callable converting a custom-type value into a value composed of natively supported types. Used during encoding. Not valid on blocked types (
bool,int,float,str,list,dict,tuple,TypedDict,NamedTuple,frozendict,Any,Literal) — attaching adump=Serializer to a blocked type raises aTypeErrorat class creation time forStruct, at construction forStructAdapter. All other types (bytes,datetime,UUID,Decimal,Enum,Structsubclasses, etc.) are accepted. The Serializer must be attached to a concrete type; see the placement rule.
- load
- Type:
Callable[[Any], Any] | None
A callable converting a value composed of natively supported types back into a custom-type value. Called during decoding (
struct_validate/struct_validate_json). Instruct_validate, an existing instance of the target type bypassesload; other Python values are passed toload. JSON input is always passed toloadbecause it starts as a decoded representation. Instruct_check_types/check_types_on_init, if the field value is not already an instance of the target type, aValidationErroris raised instead —loadis not called. Not valid on blocked types (Any,bool,int,float,str,list,dict,tuple,TypedDict,NamedTuple,frozendict,Literal). The Serializer must be attached to a concrete type; see the placement rule.
- dump¶
A callable converting a custom type value to a serializable value
- load¶
A callable converting a serializable value to a custom type value
Constraint¶
- class structtype.Constraint¶
A user-defined constraint.
- Parameters:
*args – An optional callable invoked with the annotated value after decoding/coercion. It is positional-only and stored privately as
_fn; it is not part of the public constructor interface. The return value is ignored; the callable must signal failure by raising an exception. When omitted, calling the constraint is a no-op, making bareConstraint()an inert base meant for subclassing.
Like
Serializer, aConstraintmust be attached to a concrete type insideAnnotated; see the placement rule.
NumericConstraint¶
- class structtype.NumericConstraint¶
Numeric constraints for
int/floatvalues.- Parameters:
gt (int or float, optional) – The annotated value must be greater than
gt.ge (int or float, optional) – The annotated value must be greater than or equal to
ge.lt (int or float, optional) – The annotated value must be less than
lt.le (int or float, optional) – The annotated value must be less than or equal to
le.multiple_of (int or float, optional) – The annotated value must be a multiple of
multiple_of.
StrConstraint¶
- class structtype.StrConstraint¶
Constraints for
strvalues.- Parameters:
pattern (str, optional) – A regex pattern that the annotated value must match against. Note that the pattern is treated as unanchored, meaning the
re.searchmethod is used when matching.min_length (int, optional) – The annotated value must have a length >=
min_length.max_length (int, optional) – The annotated value must have a length <=
max_length.
BytesConstraint¶
CollectionConstraint¶
- class structtype.CollectionConstraint¶
Length constraints for collection values (
list,set,frozenset, variadictuple,dict).
TimezoneConstraint¶
Unset¶
- structtype.UNSET¶
A singleton indicating a field value is unset.
This may be useful for working with message schemas where an unset field in an object needs to be treated differently than one containing an explicit
Nonevalue. In this case, you may useUNSETas the default value, rather thanNonewhen defining object schemas. This feature is supported for anystructtype.Struct,dataclassesorattrstypes.Examples
>>> from structtype import Struct, UnsetType, UNSET >>> class Example(Struct): ... x: int ... y: int | None | UnsetType = UNSET
During encoding, any field containing
UNSETis omitted from the message.>>> Example(1).struct_dump_json() b'{"x":1}' >>> Example(1, 2).struct_dump_json() b'{"x":1,"y":2}'
During decoding, if a field isn’t explicitly set in the message, the default value of
UNSETwill be set instead. This lets downstream consumers determine whether a field was left unset, or explicitly set toNone>>> Example.struct_validate_json(b'{"x": 1}') # unset Example(x=1, y=UNSET) >>> Example.struct_validate_json(b'{"x": 1, "y": null}') # explicit null Example(x=1, y=None) >>> Example.struct_validate_json(b'{"x": 1, "y": 2}') # explicit value Example(x=1, y=2)
StructAdapter¶
- class structtype.StructAdapter(type)¶
Adapter for validating and serializing types without subclassing
Struct.Useful when you want to validate or serialize plain Python types (e.g.
list[int]) without defining a fullStructsubclass.Serializer(load=...)/Serializer(dump=...)codecs are not supported onStructAdapter— annotations carrying one are rejected. Implement thestruct_dump/struct_validateprotocol methods on the custom type, or use aStruct.Constraintannotations are supported on concrete types. AConstraintattached to a union or optional type is rejected at construction, matchingStructclass creation; make the field optional withAnnotated[T, Constraint(...)] | None.>>> from structtype import StructAdapter >>> adapter = StructAdapter(list[int]) >>> adapter.struct_validate_json(b"[1, 2, 3]") [1, 2, 3]
- struct_dump(obj, *, sort_keys=False, str_keys=False, builtin_types=None)¶
Convert a validated object to built-in Python types (
dict,list, etc.).
- struct_dump_json(obj, *, decimal_as_number=False, uuid_as_hex=False, sort_keys=False)¶
Encode a validated object to JSON bytes.
- Parameters:
obj (Any) – A value to encode. Must match the adapter’s type.
decimal_as_number (bool, optional) – If True,
Decimalvalues are encoded as JSON numbers instead of strings (may lose precision when decoded).uuid_as_hex (bool, optional) – If True,
UUIDvalues are encoded as hex strings instead of canonical form.sort_keys (bool, optional) – If True, sort dict keys and set elements for deterministic output.
- struct_validate(obj, *, strict=True, from_attributes=False)¶
Validate a Python object against the adapter’s type.
- Parameters:
obj (Any) – A Python object to validate and convert.
strict (bool, optional) – If True (default), use strict type validation and coercion rules. If False, allow the documented lax-mode conversions.
from_attributes (bool, optional) – If True, accept non-dict objects by reading matching attributes. Dict input continues to match fields by serialized alias names.
- struct_validate_json(buf, *, strict=True)¶
Validate JSON bytes and decode into the adapter’s type.
Exceptions¶
- exception structtype.EncodeError¶
Bases:
ValueErrorAn error occurred while encoding an object
- exception structtype.DecodeError¶
Bases:
ValueErrorAn error occurred while decoding an object
- exception structtype.ValidationError¶
Bases:
ValueErrorThe message didn’t match the expected schema
Version¶
- structtype.__version__¶
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.
The current
structtypeversion string.