【问题标题】:Mypy type hints for arguments which are pandas series熊猫系列参数的 Mypy 类型提示
【发布时间】:2021-09-05 01:15:12
【问题描述】:

我有以下内容,我预计会引发错误:

# check.py
import pandas as pd

def f(s : str) -> None:
    print(s)

def main() -> None:
    f(s = pd.Series([1,2]))

if __name__ == "__main__":
    main()

但是,mypy check.py 返回Success: no issues found in 1 source file

应该如何为 pandas 系列提供类型提示?

在熊猫代码 (https://github.com/pandas-dev/pandas/blob/98e22297bb66f81ff4c1d4f1c3277cfe8c6b9ce7/pandas/core/series.py#L511) 中有:

    def _constructor(self) -> type[Series]:
        return Series

type[Series],我不确定我们是否应该这样输入提示系列?

编辑

将代码更新为:

# check.py
import pandas as pd

def f(s : str) -> None:
    print(s)

def g(s : str) -> None:
    print(s)

def main() -> None:
    f(s = pd.Series([1,2]))
    g(s = 12.9)

if __name__ == "__main__":
    main()

给出输出:

check.py:12: error: Argument "s" to "g" has incompatible type "float"; expected "str"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

【问题讨论】:

    标签: python pandas type-hinting mypy typing


    【解决方案1】:

    这是 mypy 中的 common issue - 如果函数没有输出类型注释,它不会检查函数类型 - 您需要将 -> None 添加到 main

    这会给你错误:

    test.py:7: error: Argument "s" to "f" has incompatible type "Series[int]"; expected "str"
    

    可以通过注解s: pd.Series[int]修复


    这是完整的脚本:

    import pandas as pd
    
    def f(s: pd.Series[int]) -> None:
        print(s)
    
    def main() -> None:
        f(s = pd.Series([1,2]))
    
    if __name__ == "__main__":
        main()
    

    注意:您可能还需要 pip install data-science-types 因为根据您安装 pandas 的方式,它可能不附带类型存根。

    【讨论】:

    • 谢谢 - 您尝试过原始代码吗?我只是用-> None 替换,仍然没有错误输出,大概应该有。我想这个 repo 中一定有一些奇怪的配置或其他东西:/
    • 是的,完全复制了您的代码,没有出现 mypy 错误,然后添加了 -> None 并得到了我复制到答案中的错误。
    • 它起初确实说由于不知道类型而跳过了对 pandas 相关代码的所有检查 - 您是否尝试安装 data-science-types 库来添加这些检查?
    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2019-07-04
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多