【问题标题】:mypy error when reshaping an array with a list of tuples使用元组列表重塑数组时出现 mypy 错误
【发布时间】:2022-01-14 06:23:29
【问题描述】:

我有一个如下所示的 python 模块:

import numpy as np

def test(order: str = 'C') -> np.ndarray:
    return np.array([1,2,3]).reshape((1,2), order = order)

用 mypy 评估它会返回错误和注释

error: No overload variant of "reshape" of "_ArrayOrScalarCommon" matches argument types "Tuple[int, int]", "str"
note: Possible overload variants:
note:     def reshape(self, Sequence[int], *, order: Union[Literal['A'], Literal['C'], Literal['F'], None] = ...) -> ndarray
note:     def reshape(self, *shape: int, order: Union[Literal['A'], Literal['C'], Literal['F'], None] = ...) -> ndarray

将函数调用中的部分 order = order 替换为 order = 'C' 可以防止发生此错误。如果我选择将此参数作为函数参数传递,为什么 mypy 会出现问题?

【问题讨论】:

    标签: python type-hinting mypy


    【解决方案1】:

    test(order: str = 'C')只设置参数C的默认值 但您仍然可以使用任何str 调用它。例如test('X') 是 正确输入。但这会导致test 调用reshape order='X' 这是错误的,这就是 mypy 抱怨的原因,这是 好东西。

    所以问题出在order的类型定义上。你可以改变 它与reshape 签名匹配,mypy 对此很满意:

    import typing as tp
    import numpy as np
    
    def test(order: tp.Optional[tp.Literal['A', 'C', 'F']] = 'C') -> np.ndarray:
        return np.array([1,2,3]).reshape((1,2), order = order)
    
    test('C')  # ok
    test('X')  # mypy error
    

    【讨论】:

    • 我明白了。是否也有数字的等价物,例如如果我只想允许一组指定的整数作为函数参数
    • @hhhh Literal 也适用于整数。例如,这是有效的:x: tp.Literal[1, 2, 3] = 2,这将引发错误:x: tp.Literal[1, 2, 3] = 4
    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 2019-02-05
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多