如何在 Python aioinflux 中将提示对象键入为 `PointType`?

How to type hint object as `PointType` in Python aioinflux?

我有一个数据class 类似于文档中定义的数据:

from dataclasses import dataclass

@lineprotocol
@dataclass
class Trade:
    timestamp: TIMEINT
    instrument: TAGENUM
    source: TAG
    side: TAG
    price: FLOAT
    size: INT
    trade_id: STR

当我尝试在 aioinflux write(data: PointType) 方法中插入此 class 的对象时,我收到一条静态类型警告,指出我的对象不是 PointType。我使用 PointType 作为我输入的类型提示,因为这是 write() 方法接受的类型。如何使我的 class return 对象成为 PointType 类型?

您可以将数据类对象转换为字典并传递给 write 方法。因为PointType是类型变量which is defined as.

if pd:
    PointType = TypeVar('PointType', Mapping, dict, bytes, pd.DataFrame)
    .....
else:
    PointType = TypeVar('PointType', Mapping, dict, bytes) 
    .....

这意味着 PointType 必须完全是 mappingdictbytespd.DataFrame 类型(如果安装了 pandas )

dataclasses 模块已经提供了转换函数dataclass obj to a dict,这足以让静态类型检查器开心!

from dataclasses import asdict
your_write_method(asdict(your_dataclass_object))

正如另一个答案所建议的那样,您可以使 class 继承自 PointType 是其实例的一种类型。 dict 在我的案例中是这样工作的:

from dataclasses import dataclass

@lineprotocol
@dataclass
class Trade(dict):
    timestamp: TIMEINT
    instrument: TAGENUM
    source: TAG
    side: TAG
    price: FLOAT
    size: INT
    trade_id: STR