如何在python aioinflux中键入``pointtype''tempe对象?

发布于 2025-01-21 04:56:54 字数 449 浏览 5 评论 0原文

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

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(数据:pointType)方法中插入该类的对象时PointType。我使用pointType用于提示我的输入的类型,因为这是write()方法接受的类型。如何使我的类返回对象的pointType类型?

I have a dataclass similar to the one defined in the docs :

from dataclasses import dataclass

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

when I try to insert objects of this class in aioinflux write(data: PointType) method I get a static typing warning that my object is not of PointType. I used PointType for type hinting my input because this is the type that the write() method accepts. How can I make my class return objects of PointType type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谜兔 2025-01-28 04:56:54

您可以将数据级对象转换为词典,然后传递到Write方法中。因为pointType是类型变量定义为

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

这意味着pointType必须完全是类型映射dictbytespd.dataframe < /code>(如果安装了熊猫)

Dataclasses模块已经提供了一个函数来转换 dataclass obj to dict 足以使静态类型的检查器快乐!

from dataclasses import asdict
your_write_method(asdict(your_dataclass_object))

You can convert your dataclass object into a dictionary and pass into write method. Because PointType is a type variable which is defined as.

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

This means that PointType must be exactly of type mapping or dict or bytes or pd.DataFrame(if pandas is installed)

The dataclasses module already provides a function to convert dataclass obj to a dict which is sufficient to make the static type checker happy!

from dataclasses import asdict
your_write_method(asdict(your_dataclass_object))
乖不如嘢 2025-01-28 04:56:54

正如另一个答案表明,您可以从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

as the other answer suggest you can make your class inherit from one of the types that the PointType is an instance of. dict worked in my case like this:

from dataclasses import dataclass

@lineprotocol
@dataclass
class Trade(dict):
    timestamp: TIMEINT
    instrument: TAGENUM
    source: TAG
    side: TAG
    price: FLOAT
    size: INT
    trade_id: STR
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文