繁体   English   中英

文字作为泛型的一部分——python 打字

[英]Literal as part of generic type -- python typing

假设我想在 Python 中设计一个Array数据类型。它旨在容纳特定类型的固定大小列表。

T = typing.TypeVar('T')
class Array(typing.Generic[T]):
  l: list[T]
  s: int

所以类型提示是这样的:

fixed_size_array: Array[int]

我想要做的是在类型提示中包含Array的长度,例如:

fixed_size_array_of_five_ints: Array[int, 5]
fixed_size_array_of_four_ints: Array[int, 4]

我可以更改Array的实现,因为我唯一的要求是Array[int, 5]的类型提示或包含文字/常量大小的内容。

这可能吗?

您可以使用文字 [...]:

T = typing.TypeVar('T')
S = typing.TypeVar('S')

class Array(typing.Generic[T, S]):
  l: list[T]
  s: S
  def __init__(self, s: S):
    self.l = []
    #...
    self.s = s

def typed_array_op(a: T, b: T) -> T:
  return some_func(a, b)

#...

a2: Array[int, Literal[2]]
b2: Array[int, Literal[2]]
a3: Array[int, Literal[3]]

a2 = array(2)
a3 = array(2) # mypy error

typed_array_op(a2, b2)
typed_array_op(a2, a3) # mypy error

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM