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_config class attribute using a StructConfig dict (see example below). These configuration options may also be inspected at runtime through the __struct_config__ attribute. The sparse struct_config attribute 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_field for configuring tagged union support. If either are non-None, then the struct is considered “tagged”. In this case, an extra field (the tag_field) and value (the tag) are added to the encoded message, which can be used to differentiate message types during decoding.

    Set tag=True to enable the default tagged configuration (tag_field is "type", tag is 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 tag is non-None, then this defaults to "type". See the tag docs 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 or None to not rename that field. Default is None for 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 a ValidationError if any value does not match. Default is False.

Examples

Here we define a new Struct type 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_config class attribute. Here we define a new Struct type for a frozen Point object.

>>> 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__
Type:

tuple[str, …]

A tuple of the field names in declaration order. Available on both the struct type and on instances.

__struct_alias_fields__
Type:

tuple[str, …]

A tuple of the field names used for serialization, in declaration order. These are the field names after applying any rename configuration. 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:

StructConfig

The StructConfig for this struct type. Available on both the struct type and on instances.

struct_config
Type:

StructConfig

The StructConfig dict 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__
Type:

tuple[str, …]

A tuple of the field names used for positional pattern matching. Available on the struct type.

__signature__
Type:

inspect.Signature

The computed __init__ signature for the struct type. Available on the struct type.

__slots__
Type:

tuple[str, …]

The field names stored as instance slots. On the base Struct class this is empty; subclasses get one slot per field.

__iter__()

Iterate over the struct as (name, value) pairs in declaration order. This enables dict(p), list(p), and iter(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.dump and copy.deepcopy support.

__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 a UserWarning when a new field’s name starts with struct_ and matches a known struct member (the struct_* methods above or struct_config). A struct_-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. Use warnings.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 a ValidationError if 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.load and protocol fallbacks are skipped). Any annotated Constraint is still called on correctly-typed values.

If check_types_on_init=True was 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_json but produces Python objects instead of JSON bytes:

  • Struct-level settings are honored: rename, omit_defaults, array_like, and tag for tagged unions.

  • Fields containing UNSET are 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 is False.

  • 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. Use ALL_BUILTIN_TYPES as a shortcut to pass through all supported types.

Returns:

dict or list – The converted object. For array_like=False structs returns a dict. For array_like=True structs returns a list.

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.Decimal values are encoded. If False (default), encodes as JSON strings. If True, encodes as JSON numbers (may lose precision when decoded by some libraries).

  • uuid_as_hex (bool, optional) – Controls how uuid.UUID values are encoded. If False (default), encodes in canonical form (xxxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx). If True, 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 is False.

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 is True.

  • 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 is False.

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_values become 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.

Parameters:
  • buf (str or bytes-like) – The JSON message to decode.

  • 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. Default is True.

Returns:

Self – A new struct instance.

class structtype.StructMeta(name, bases, namespace, /)

The metaclass for creating Struct types. See its documentation for the available configuration options when subclassing.

Struct configuration is provided via a struct_config class attribute in the class body, using a StructConfig dict.

For project-wide config defaults, prefer a base Struct class with a struct_config attribute — no custom metaclass is needed.

StructMeta can be subclassed, and may be combined with abc.ABCMeta to 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 the struct_config class attribute.

structtype.fields(type_or_instance)

Get introspection information about a struct’s fields.

Returns a tuple of FieldInfo objects 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_components instead.

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 as template.format(name=name). This can be useful if you intend to store the components mapping somewhere other than a top-level "$defs" field. For example, you might use ref_template="#/components/{name}" if generating an OpenAPI schema.

Returns:

schema (dict) – The generated JSON Schema.

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.

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.

  • ref_template (str, optional) – A template to use when generating "$ref" fields.

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 components dict.

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 as template.format(name=name). This can be useful if you intend to store the components mapping somewhere other than a top-level "$defs" field. For example, you might use ref_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 one FieldInfo per 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

FieldInfo is the read side of field metadata — you obtain it by calling structtype.fields(). To set metadata (aliases, descriptions, JSON schema extra, …) on a field, use typing.Annotated with Field in 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=...) or StructConfig(rename=...) is used.

type

The field’s type annotation.

default

The default value, or NODEFAULT for required fields.

default_factory

A callable that produces the default value, or NODEFAULT if 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_config attribute. Keys not present inherit from the base class; __struct_config__ returns the fully-resolved dict. struct_config returns exactly what the user wrote (sparse dict), and is always present — it defaults to {} when never declared.

A typing.TypedDict with total=False containing 15 optional keys. StructConfig(frozen=True) returns a plain dict at runtime.

Important

isinstance(x, StructConfig) raises TypeError on all Python versions. Use isinstance(x, dict) instead, or access individual keys directly.

Keys:

frozen
Type:

bool

Make instances immutable — setattr/delattr raise FrozenInstanceError. Enables __hash__ (only when eq=True, the default). See Frozen Instances.

eq
Type:

bool

Generate __eq__ and __ne__. Enabled by default.

order
Type:

bool

Generate __lt__, __le__, __gt__, __ge__. Requires eq=True. See Equality and Order.

kw_only
Type:

bool

All fields are keyword-only in __init__ when enabled. Disabled by default.

repr_omit_defaults
Type:

bool

Omit fields equal to their default value in __repr__. Described in Configuration Inheritance.

array_like
Type:

bool

Encode as positional array (list/tuple) instead of a JSON object. Described in Supported Types.

weakref
Type:

bool

Allow weakref.ref on instances (one pointer per instance). Described in Configuration Inheritance.

dict
Type:

bool

Give instances a __dict__ for arbitrary runtime attributes. Described in Configuration Inheritance.

cache_hash
Type:

bool

Cache the hash of frozen struct instances after the first hash() call. Described in Configuration Inheritance.

omit_defaults
Type:

bool

Omit fields equal to their default value in struct_dump_json output. See Omitting Default Values.

forbid_unknown_fields
Type:

bool

Raise ValidationError on unknown keys in struct_validate/struct_validate_json. See Forbidding Unknown Fields.

check_types_on_init
Type:

bool

Run type and constraint validation on every __init__ call. See check_types_on_init.

tag
Type:

bool | str | int | Callable[[str], str | int] | None

The discriminant value used for tagged unions — either a fixed value or a callable that maps the class name to one. Set to False to 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.

structtype.ALL_BUILTIN_TYPES
Type:

tuple[type, …]

A tuple of all builtin types. Can be used for struct_dump argument builtin_types to pass through all builtin types unchanged.

>>> from structtype import ALL_BUILTIN_TYPES
>>> obj.struct_dump(builtin_types=ALL_BUILTIN_TYPES)

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 rename option 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_extra overriding 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(), and bytearray()) used as defaults are shorthand for Factory(list), Factory(dict), and friends. The wrapped callable is exposed as the read-only factory attribute.

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 a dump= Serializer to a blocked type raises a TypeError at class creation time for Struct, at construction for StructAdapter. All other types (bytes, datetime, UUID, Decimal, Enum, Struct subclasses, 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). In struct_validate, an existing instance of the target type bypasses load; other Python values are passed to load. JSON input is always passed to load because it starts as a decoded representation. In struct_check_types / check_types_on_init, if the field value is not already an instance of the target type, a ValidationError is raised instead — load is 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 bare Constraint() an inert base meant for subclassing.

Like Serializer, a Constraint must be attached to a concrete type inside Annotated; see the placement rule.

NumericConstraint

class structtype.NumericConstraint

Numeric constraints for int/float values.

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 str values.

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.search method 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

class structtype.BytesConstraint

Length constraints for bytes-like values (bytes, bytearray, memoryview).

Parameters:
  • 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.

CollectionConstraint

class structtype.CollectionConstraint

Length constraints for collection values (list, set, frozenset, variadic tuple, dict).

Parameters:
  • 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.

TimezoneConstraint

class structtype.TimezoneConstraint

Timezone requirements for datetime.datetime/datetime.time values.

Parameters:

tz (bool) – Set to True to require timezone-aware values, or False to require timezone-naive values.

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 None value. In this case, you may use UNSET as the default value, rather than None when defining object schemas. This feature is supported for any structtype.Struct, dataclasses or attrs types.

Examples

>>> from structtype import Struct, UnsetType, UNSET
>>> class Example(Struct):
...     x: int
...     y: int | None | UnsetType = UNSET

During encoding, any field containing UNSET is 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 UNSET will be set instead. This lets downstream consumers determine whether a field was left unset, or explicitly set to None

>>> 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)
class structtype.UnsetType

The type of UNSET.

See also

UNSET

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 full Struct subclass.

Serializer(load=...) / Serializer(dump=...) codecs are not supported on StructAdapter — annotations carrying one are rejected. Implement the struct_dump / struct_validate protocol methods on the custom type, or use a Struct.

Constraint annotations are supported on concrete types. A Constraint attached to a union or optional type is rejected at construction, matching Struct class creation; make the field optional with Annotated[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, Decimal values are encoded as JSON numbers instead of strings (may lose precision when decoded).

  • uuid_as_hex (bool, optional) – If True, UUID values 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.

Parameters:
  • buf (str or bytes) – The JSON message to decode.

  • strict (bool, optional) – If True (default), use strict type validation and coercion rules. If False, allow the documented lax-mode conversions.

Exceptions

exception structtype.EncodeError

Bases: ValueError

An error occurred while encoding an object

exception structtype.DecodeError

Bases: ValueError

An error occurred while decoding an object

exception structtype.ValidationError

Bases: ValueError

The 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 structtype version string.