函数与异常 API
本页汇总模块级函数与调试能力。 包括序列化入口、追踪工具以及异常类型。
示例代码
from tarsio import Struct, decode_trace, encode, field
class User(Struct):
id: int = field(tag=0)
payload = encode(User(1))
obj = User.decode(payload)
trace = decode_trace(payload)
assert obj.id == 1
assert trace.jce_type == "ROOT"
核心概念
encode/decode是统一入口,按输入决定 schema 或 Raw 路径。decode_trace适合协议调试,可输出树状追踪信息。probe_struct可快速判断 bytes 是否像完整 Struct。ValidationError表示约束校验失败,不等同于二进制损坏。
注意事项
- 调试函数返回的是诊断视图,不保证和业务模型一一对应。
- 面向外部输入时应限制包体大小并做好异常分类处理。
decode的目标类型应明确,避免运行时分派歧义。
API 参考
tarsio.encode
将对象序列化为 Tars 二进制格式.
该函数会自动根据输入对象的类型选择合适的编码模式:
1. Schema 模式:如果对象是 Struct、dataclass、NamedTuple 或 TypedDict 实例,
将按照其定义的 Schema 进行编码。
2. Raw 模式:如果对象是 TarsDict、 dict、list 或基本类型,
将进行原始编码(无 Schema)。
| 参数 | 描述 |
|---|---|
obj
|
要编码的对象。
类型:
|
| 返回 | 描述 |
|---|---|
bytes
|
包含序列化数据的 bytes 对象。 |
| 引发 | 描述 |
|---|---|
TypeError
|
如果对象既不是有效的 Struct 也不是支持的 Raw 类型。 |
ValueError
|
如果数据校验失败。 |
源代码位于: python/tarsio/api.py
tarsio.decode
decode(data: _BytesLike, cls: type[_StructT]) -> _StructT
从 Tars 二进制数据反序列化.
| 参数 | 描述 |
|---|---|
cls
|
目标类 |
data
|
二进制数据
类型:
|
| 返回 | 描述 |
|---|---|
Any
|
反序列化的类实例或 TarsDict。 |
| 引发 | 描述 |
|---|---|
TypeError
|
参数类型错误或目标类未注册 Schema。 |
ValueError
|
数据格式不正确。 |
源代码位于: python/tarsio/api.py
tarsio.probe_struct
builtin
tarsio.decode_trace
builtin
解析二进制数据并生成追踪树.
tarsio.TraceNode
decode_trace 返回的调试树节点.
| 属性 | 描述 |
|---|---|
tag |
当前节点对应的 Tag。
类型:
|
jce_type |
JCE 类型名。
类型:
|
value |
当前节点值(容器节点通常为 None)。
类型:
|
children |
子节点列表。 |
name |
字段名(有 Schema 时可用)。
类型:
|
type_name |
类型名(有 Schema 时可用)。
类型:
|
path |
从根开始的可读路径。
类型:
|
__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.ValidationError
Bases: builtins.ValueError
解码阶段的校验错误.
由 Meta 约束或 Schema 校验失败触发。
错误消息包含路径与原因,典型格式:
Error at <root>.<field>.<tag:N>: <reason>。
Notes
当前版本不提供结构化字段访问器(如 field_name、tag 属性)。
建议在业务侧解析异常消息中的路径片段。
__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'.