You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python类型自动推断pyarrow.DataType?

解决方案

方法1:通过实际属性值自动推断Arrow类型

PyArrow提供了pa.scalar()方法,可直接从Python对象生成Arrow标量,同时获取其对应的Arrow类型,完全替代手动维护的ArrowTypes字典:

修改StructLike类中的arrow_type方法,并简化冗余代码:

from typing import Any, get_type_hints
import pyarrow as pa
import pyarrow.compute as pac

class StructLike:
    __attr_annotations__: dict[str, Any]

    def __init__(self):
        self.__dict__["__attr_annotations__"] = get_type_hints(self)

    def __setattr__(self, name: str, value: Any) -> None:
        try:
            expected_type = self.__attr_annotations__[name]
            if isinstance(value, expected_type):
                self.__dict__[name] = value
            else:
                raise TypeError(
                    f"'{name}' should have type {expected_type}, but instead it has type {type(value)}"
                )
        except TypeError as e:
            raise e
        except KeyError:
            raise KeyError(f"Could not find '{name}' in {self.__attr_annotations__=}")

    def as_dict(self) -> dict[str, Any]:
        return {k: getattr(self, k) for k in self.__attr_annotations__.keys()}
    
    def arrow_type(self) -> pa.StructType:
        fields = []
        for name in self.__attr_annotations__.keys():
            value = getattr(self, name)
            # 从属性值自动匹配Arrow类型
            scalar_type = pa.scalar(value).type
            fields.append(pa.field(name, scalar_type))
        return pa.struct(fields)

    def to_arrow(self) -> pa.StructScalar:
        return pac.cast(
            self.as_dict(),
            target_type=self.arrow_type(),
        )

原测试代码无需修改,运行后仍会输出预期的StructScalar,且现在自动支持float、bool等更多基础类型,无需手动更新映射关系。

方法2:基于类型注解直接推断Arrow类型

如果不想依赖实际属性值,可直接从类的类型注解生成Arrow结构,使用PyArrow内置的pa.from_type_hints工具:

def arrow_type(self) -> pa.StructType:
    # 直接从类型注解生成Arrow Schema
    return pa.from_type_hints(self)

这种方法无需等待属性赋值,就能提前获取Arrow结构,但仅支持PyArrow内置兼容的基础类型注解。


内容的提问来源于stack exchange,提问作者bzm3r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 16:29:56