小编bon*_*ris的帖子

Python - 打字 - 可下标类型的联合

我想创建一个Array类型,它应该是可下标的并且是typing.Listnumpy.ndarray类型的联合。我知道numpy没有存根,但是那些 numpy 存根(由Machinalis 提供)应该可以正常工作,因为它们是可订阅的。

这是预期的行为:

def foo(bar: Array[int])->None:
    pass

foo([1,2,3])          # No typing error
foo(numpy.arange(4))  # No typing error
foo((1,2,3))          # Error: Expected Array[int], got Tuple[int]
foo([1.,2.,3.])       # Error: Expected Array[int], got Array[float]
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一些东西,但没有一个像预期的那样工作。

你会如何在 Python 3.7 中做到这一点?

我也会接受某种鸭子类型的解决方案,即使它不满足元组错误。重点是创建可下标类型的可下标联合。

谢谢。

我最好的尝试:(评论中的 mypy 错误)

class _meta_getitem(type):
    def __getitem__(cls, x):
        return cls.__getitem__(cls, x)

class Array(metaclass=_meta_getitem):

    def __getitem__(self, element_type: type) -> type:
        array_type = typing.Union[List[element_type],  # error: Invalid …
Run Code Online (Sandbox Code Playgroud)

python numpy type-hinting python-3.x mypy

6
推荐指数
1
解决办法
3274
查看次数

标签 统计

mypy ×1

numpy ×1

python ×1

python-3.x ×1

type-hinting ×1