[Question] Integer `Literal` arithmetic for, *e.g.*, physical units?
还没有人认领这个 Issue。
评估
调研方向
首先阅读所引用的 PEP 827,并将其中的数组形状示例与本 issue 中的 Unit 和 Quantity 玩具实现进行比较。确定 integer Literal arithmetic、生成的 integer Literal ranges 以及 dimension checks 是否符合该提案;完成的标准是记录受支持的行为以及任何所需的类型系统更改。
由索引模型根据 Issue 内容生成。
描述
Hello! Apologies beforehand for polluting the repo's issues with questions tangential to PEP 827.
For the past few days I've been banging my head against Python's type system trying to replace a dependency on the otherwise excellent pint library with my own bare-bones implementation. I'm by no means a computer scientist nor a professional programmer, so I've struggled to come up with a way to express physical units' dimensionality through the type system.
While racking my brain I came upon PEP 827 and I found the array shape example particularly fitting. Does your current proposal allow for performing arithmetic operations on integer literals? E.g., Literal[1] + Literal[2] resolving to Literal[3]. Is there even a way to represent any integer literal similarly to LiteralString?
For further context, here is a toy example of what I'm trying to achieve:
from decimal import Decimal
from fractions import Fraction
from typing import Any, Literal, Self, final, overload, reveal_type
from typemap_extensions import GetArg, IsAssignable, RaiseError
type Range[T] = tuple[Literal[i] for i in ...] # How would one generate a tuple of integer `Literal`s?
type AddDims[T, S] = (
tuple[GetArg[T, tuple, i] + GetArg[S, tuple, i] for i in Range[Length[T]]] # Can integer `Literal`s be added?
if IsAssignable[Length[T], Length[S]] # Units belong to same system
else RaiseError[Literal["Incompatible unit system"], T, S]
)
type EqDims[T, S] = (
T
if IsAssignable[T, S]
else RaiseError[Literal["Incompatible dimensions"], T, S]
)
@final
class Unit[*T]:
"""Physical unit abstraction."""
def __init__(self: Self, dimensions: tuple[*T], /) -> None:
"""Infer dimensionality from exponents."""
self.dimensions: tuple[*T] = dimensions
@overload
def __mul__[*S](
self: Self, other: Unit[*S], /
) -> Unit[AddDims[tuple[*T], tuple[*S]]]: ...
@overload
def __mul__[S: (Decimal, Fraction)](
self: Self, other: S, /
) -> Quantity[S, *T]: ...
def __mul__(self: Self, other: Any, /) -> Any:
"""Return `Unit` with computed dimensions or `Quantity`."""
raise NotImplementedError()
def __rmul__[S: (Decimal, Fraction)](
self: Self, other: S, /
) -> Quantity[S, *T]:
"""Return `Quantity` from scalar and `Unit`."""
raise NotImplementedError()
@final
class Quantity[T: (Decimal, Fraction), *S]:
"""Physical quantity abstraction."""
def __init__(self: Self, magnitude: T, unit: Unit[*S], /) -> None:
"""Infer dimensionality from `Unit`."""
self.magnitude: T = magnitude
self.unit: Unit[*S] = unit
def __add__[*U](
self: Self, other: Quantity[T, *U], /
) -> Quantity[T, EqDims[tuple[*S], tuple[*U]]]:
"""Disallow addition when dimensions do not match."""
raise NotImplementedError()
# Expected behavior:
s = Unit((0, 1))
mps = Unit((1, -1))
reveal_type(s) # Unit[Literal[0], Literal[1]]
reveal_type(mps) # Unit[Literal[1], Literal[-1]]
m = s * mps
reveal_type(m) # Unit[Literal[1], Literal[0]]
dist = Decimal(10) * m
speed = Decimal(1) * mps
reveal_type(dist) # Quantity[Decimal, Unit[Literal[1], Literal[0]]
reveal_type(speed) # Quantity[Decimal, Unit[Literal[1], Literal[-1]]]
reveal_type(dist + dist) # Quantity[Decimal, Unit[Literal[1], Literal[0]]]
reveal_type(dist + speed) # Error: Incompatible dimensions
Range and AddDims are pseudo-code; I'm not exactly sure whether the operation would be allowed and whether that's how you'd retrieve the exponent from the tuple.
Does this kind of behavior fit within the scope of the PEP? Or would it require additional modifications to the type system such as allowing subclassing or changing how Literals are inferred?
Looking forward to hearing what becomes of the PEP regardless; we're all sure to find some interesting applications for the proposed additions!
- 主要语言
- Python
- 星标
- 25
- 派生
- 3
- 平均合并
- 23 分钟
- 30 天内合并 PR
- 2
环境准备
这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
vercel-labs/python-typemap 的其他 Issue
-
难度 4/5 3-5 天 新手友好度 42/100
vercel-labs/python-typemap#123 ·
查看 vercel-labs/python-typemap 的全部 Issue
相似的 Issue
-
难度 2/5 1-3 小时 新手友好度 82/100
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 70/100
onyx-dot-app/onyx#16016 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 72/100
维护者通常 1 天内回复
-
black --check exits 0 and prints All done when a multi file run is interrupted可能已有人在做 @jiteshgulati 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 72/100
维护者通常 2 天内回复
-
Non-positive worker counts wait for results without starting workers可能已有人在做 @IlyaKhalafi 今天认领。 未关闭
难度 2/5 1-3 小时 新手友好度 85/100
维护者通常 1 天内回复