跳转至

Struct 与字段 API

本页汇总 Struct 建模相关的公共 API。 行为细节以类型注解、默认值和配置项的可观察结果为准。

示例代码

from typing import Annotated
from tarsio import Meta, Struct, field

class User(Struct, frozen=True, omit_defaults=True):
    id: int = field(tag=0)
    name: str = field(tag=1)
    score: Annotated[int, Meta(ge=0)] = field(tag=2, default=0)

核心概念

  • Struct 是 schema 入口,自动生成构造、比较与编码行为。
  • field 用于声明 Tag、默认值、default_factorywrap_simplelist
  • Meta 描述解码约束,失败时抛 ValidationError
  • StructConfig 记录类定义时启用的配置快照。
  • TarsDict 是 Raw Struct 语义容器,不等同于普通 dict
  • Raw 路径下,Struct 可在任意嵌套位置编码,且 StructBegin 在任意嵌套层级统一还原为 TarsDict
  • Struct/TarsDict 字段可使用 field(wrap_simplelist=True):先按原类型编码,再将该字段包装为 SimpleList(bytes)

注意事项

  • Struct 配置会影响构造行为与编码结果,建议在模型层统一约定。
  • __post_init__ 中抛 TypeError/ValueError 会被视为校验失败路径。
  • 协议演进中如需严格拒绝未知字段,可使用 forbid_unknown_tags=True
  • wrap_simplelist=True 仅支持 Struct/TarsDict 字段,解码严格要求 wire 为 SimpleList(bytes),不做回退。

API 参考

tarsio.Struct

Struct(*args, **kwargs)

Bases: tarsio._core._StructBase

高性能可序列化结构体基类.

Struct 用于定义可编码/解码的 Tars/JCE 数据结构。字段通过类型注解声明, tag 支持显式与隐式混合:

  • 显式 tag:通过 field(tag=...) 指定。
  • 隐式 tag:未显式指定时按字段定义顺序自动分配。 当未显式指定的字段位于显式 tag 字段之后时,会从该显式 tag 继续递增分配。

Annotated 仅用于附加 Meta 约束,不再负责声明 tag。

字段可以提供默认值。带默认值的字段在构造函数中表现为可选参数;当字段是 Optional 且未 显式提供默认值时,其默认值视为 None

Struct 会提供/生成以下能力:

  • __init__:支持按 Tag 顺序的 positional 参数,以及按字段名的 keyword 参数。
  • __eq__:当 eq=True 时生成相等比较。
  • __repr__:生成可读的 repr;当 repr_omit_defaults=True 时省略默认值字段。
  • __copy__:生成浅拷贝。
  • __post_init__:若定义则在实例初始化完成后调用(包括解码路径)。
  • __replace__:返回替换指定字段后的新实例。
  • __match_args__:用于模式匹配的位置参数顺序。
  • __rich_repr__:为 rich pretty-print 提供字段迭代项。
  • 排序比较:当 order=True 时生成 __lt__/__le__/__gt__/__ge__
  • Hash: 当 frozen=True 时提供 __hash__(使实例可哈希)。

运行时元信息:

  • __struct_fields__:字段名元组,按 Tag 升序排列。
  • __struct_config__:配置对象(见 StructConfig)。
Configuration

可在定义 Struct 子类时传入关键字参数控制行为:

  • frozen (bool, default False): 是否冻结实例。冻结后禁止属性赋值,并提供 __hash__
  • order (bool, default False): 是否生成排序比较方法。
  • eq (bool, default True): 是否生成 __eq__
  • kw_only (bool, default False): 是否将所有字段设为仅关键字参数。
  • omit_defaults (bool, default False): 编码时是否省略值等于默认值的字段。
  • repr_omit_defaults (bool, default False): repr 是否省略值等于默认值的字段。
  • forbid_unknown_tags (bool, default False): 解码时是否禁止出现未知 Tag.
  • dict (bool, default False): 是否为实例保留 __dict__(允许附加额外属性)。
  • weakref (bool, default False): 是否支持弱引用。

示例:

基本用法:

from typing import Annotated
from tarsio import Meta, Struct, field

class User(Struct):
    uid: int = field(tag=0)
    name: str  # 自动分配 tag=1
    score: Annotated[int, Meta(ge=0)] = field(tag=2, default=0)

user = User(uid=1, name="Ada")
data = user.encode()
restored = User.decode(data)
assert restored == user

启用配置项:

from tarsio import Struct, field

class Point(Struct, frozen=True, order=True):
    x: int = field(tag=0)
    y: int = field(tag=1)

encode

encode() -> bytes

将当前实例编码为 Tars 二进制数据.

返回 描述
bytes

编码后的 bytes。

引发 描述
ValueError

缺少必填字段或类型不匹配。

decode classmethod

decode(data: _BytesLike) -> _StructT

将 Tars 二进制数据解码为当前类实例.

参数 描述
data

待解码的 bytes。

类型: _BytesLike

返回 描述
_StructT

解码得到的实例。

引发 描述
TypeError

目标类未注册 Schema。

ValueError

数据格式不正确或缺少必填字段。

ValidationError

解码后 __post_init__ 抛出 TypeError/ValueError。

tarsio.StructMeta

Bases: builtins.type

Struct 的元类.

用于在定义 Struct 子类时,在类创建期编译并注册 Schema,并生成相应的构造行为与 运行时元信息(如 __struct_fields____struct_config____signature__)。

tarsio.StructConfig

Struct 的配置对象.

该对象反映 Struct 子类在定义时传入的配置选项,可通过 Struct.__struct_config__ 或实例的 __struct_config__ 访问。

属性 描述
frozen

是否冻结实例(不可变)。

类型: bool

eq

是否启用值相等比较。

类型: bool

order

是否启用排序比较。

类型: bool

kw_only

构造函数是否仅接受关键字参数。

类型: bool

repr_omit_defaults

repr 是否省略默认值字段。

类型: bool

omit_defaults

编码时是否省略默认值字段。

类型: bool

weakref

是否支持弱引用。

类型: bool

dict

是否保留 __dict__(允许动态属性)。

类型: bool

rename

预留字段(当前默认未启用)。

类型: Any | None

__module__ class-attribute

__module__ = 'tarsio._core'

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 sys.getdefaultencoding(). errors defaults to 'strict'.

dict property

dict: bool

eq property

eq: bool

frozen property

frozen: bool

kw_only property

kw_only: bool

omit_defaults property

omit_defaults: bool

order property

order: bool

rename property

rename: Any | None

repr_omit_defaults property

repr_omit_defaults: bool

weakref property

weakref: bool

tarsio.Meta

Meta(
    gt: float | None = ...,
    lt: float | None = ...,
    ge: float | None = ...,
    le: float | None = ...,
    min_len: int | None = ...,
    max_len: int | None = ...,
    pattern: str | None = ...,
)

字段元数据与约束定义.

初始化字段元数据.

参数 描述
gt

数值必须大于该值。

类型: float | None 默认: ...

lt

数值必须小于该值。

类型: float | None 默认: ...

ge

数值必须大于或等于该值。

类型: float | None 默认: ...

le

数值必须小于或等于该值。

类型: float | None 默认: ...

min_len

长度下限。

类型: int | None 默认: ...

max_len

长度上限。

类型: int | None 默认: ...

pattern

正则表达式约束。

类型: str | None 默认: ...

__doc__ class-attribute

__doc__ = '字段元数据与约束定义.'

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 sys.getdefaultencoding(). errors defaults to 'strict'.

__module__ class-attribute

__module__ = 'tarsio._core'

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 sys.getdefaultencoding(). errors defaults to 'strict'.

__new__ builtin

__new__(*args, **kwargs)

Create and return a new object. See help(type) for accurate signature.

ge property

ge: float | None

gt property

gt: float | None

le property

le: float | None

lt property

lt: float | None

max_len property

max_len: int | None

min_len property

min_len: int | None

pattern property

pattern: str | None

tarsio.field builtin

field(**kwargs) -> Any

创建字段默认值规格.

返回 描述
Any

内部 _FieldSpec 对象。

引发 描述
TypeError

参数非法、未知关键字、或默认值与工厂冲突时抛出。

tarsio.NODEFAULT module-attribute

NODEFAULT: Final[object] = NODEFAULT

field 默认值哨兵类型.

tarsio.TarsDict

Bases: builtins.dict

__doc__ class-attribute

__doc__ = ''

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 sys.getdefaultencoding(). errors defaults to 'strict'.

__module__ class-attribute

__module__ = 'tarsio._core'

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 sys.getdefaultencoding(). errors defaults to 'strict'.

__new__ builtin

__new__(*args, **kwargs)

Create and return a new object. See help(type) for accurate signature.