将参数注释为 np.ndarray 有什么意义?

问题描述

假设我有以下文件 t2.py

import numpy as np
from typing import Dict,Any

def func(arr: np.ndarray):
    arr.to_json()
    arr.to_jason()

class MyClass:
    def to_json(self) -> Dict[str,Any]: ...

def my_func(arr: MyClass):
    arr.to_json()
    arr.to_jason()

如果我运行 mypy 我得到

$ mypy t2.py --ignore-missing-imports
t2.py:13: error: "MyClass" has no attribute "to_jason"; maybe "to_json"?
Found 1 error in 1 file (checked 1 source file)

因此,在 func2 中,当我将 arr 注释为 MyClass 然后对其调用不存在的方法时,mypy 发现了错误。但是当我在 func调用不存在的方法时,arr 并没有发生同样的情况,注释为 np.ndarray

确实,如果我使用 reveal_type,那么在 func 中我看到它是 Any 类型。

然而,我看到很多人在他们的代码中将变量注释为 np.ndarray。人们为什么要这样做?只是为了可读性,还是可以帮助 mypy 真正找到任何错误

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)