使用Python类型提示在数字上强制使用单位

2024-09-27 09:31:23 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法将Python类型提示作为单元使用?type hint docs显示了一些示例,这些示例表明使用^{}可能是可行的,但这些示例还显示,添加两个相同“新类型”的值不会产生“新类型”的结果,而是产生基类型。是否有一种方法可以丰富类型定义,以便您可以指定类似于单位的类型提示(不是在它们转换时,而是在您获得不同单位时得到类型警告)?允许我这样做或类似的事情:

Seconds = UnitType('Seconds', float)
Meters = UnitType('Meters', float)

time1 = Seconds(5)+ Seconds(8) # gives a value of type `Seconds`
bad_units1 = Seconds(1) + Meters(5) # gives a type hint error, but probably works at runtime
time2 = Seconds(1)*5 # equivalent to `Seconds(1*5)` 
# Multiplying units together of course get tricky, so I'm not concerned about that now.

我知道存在用于单元的运行时库,但我好奇的是python中的类型提示是否能够处理其中的一些功能


Tags: of方法示例docs类型type单位float
1条回答
网友
1楼 · 发布于 2024-09-27 09:31:23

答案不就在那里on the page你链接了吗

from typing import NewType

Seconds = NewType('Seconds', float)
Meters = NewType('Meters', float)

time1 = Seconds(5)+ Seconds(8) # gives a value of type `Seconds`
bad_units1 = Seconds(1) + Meters(5) # gives a type hint error, but probably works at runtime
time2 = Seconds(1)*5 # equivalent to `Seconds(1*5)` 

看起来,因为we can't pass a value, only a type, into a generic,所以不可能进行全维分析as available in Adaimplementable in C++

相关问题 更多 >

    热门问题