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_factory与wrap_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
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
decode
classmethod
将 Tars 二进制数据解码为当前类实例.
| 参数 | 描述 |
|---|---|
data
|
待解码的 bytes。
类型:
|
| 返回 | 描述 |
|---|---|
_StructT
|
解码得到的实例。 |
| 引发 | 描述 |
|---|---|
TypeError
|
目标类未注册 Schema。 |
ValueError
|
数据格式不正确或缺少必填字段。 |
ValidationError
|
解码后 |
tarsio.StructMeta
Bases: builtins.type
Struct 的元类.
用于在定义 Struct 子类时,在类创建期编译并注册 Schema,并生成相应的构造行为与
运行时元信息(如 __struct_fields__、__struct_config__、__signature__)。
tarsio.StructConfig
Struct 的配置对象.
该对象反映 Struct 子类在定义时传入的配置选项,可通过
Struct.__struct_config__ 或实例的 __struct_config__ 访问。
| 属性 | 描述 |
|---|---|
frozen |
是否冻结实例(不可变)。
类型:
|
eq |
是否启用值相等比较。
类型:
|
order |
是否启用排序比较。
类型:
|
kw_only |
构造函数是否仅接受关键字参数。
类型:
|
repr_omit_defaults |
类型:
|
omit_defaults |
编码时是否省略默认值字段。
类型:
|
weakref |
是否支持弱引用。
类型:
|
dict |
是否保留
类型:
|
rename |
预留字段(当前默认未启用)。
类型:
|
__module__
class-attribute
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'.
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
|
数值必须大于该值。
类型:
|
lt
|
数值必须小于该值。
类型:
|
ge
|
数值必须大于或等于该值。
类型:
|
le
|
数值必须小于或等于该值。
类型:
|
min_len
|
长度下限。
类型:
|
max_len
|
长度上限。
类型:
|
pattern
|
正则表达式约束。
类型:
|
__doc__
class-attribute
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
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
Create and return a new object. See help(type) for accurate signature.
tarsio.field
builtin
field(**kwargs) -> Any
tarsio.TarsDict
Bases: builtins.dict
__doc__
class-attribute
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
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'.