简体   繁体   English

如何在 Mypy 中干净地测试对象的相等性而不产生错误?

[英]How do I cleanly test equality of objects in Mypy without producing errors?

I have the following function:我有以下 function:

import pandas as pd

def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
    return left == right

I get the following error when I run it through Mypy:通过 Mypy 运行它时出现以下错误:

error: Returning Any from function declared to return "bool"错误:从 function 返回 Any 声明返回“bool”

I believe this is because Mypy doesn't know about pd.Timestamp so treats it as Any .我相信这是因为 Mypy 不知道pd.Timestamp所以把它当作Any (Using the Mypy reveal_type function shows that Mypy treats left and right as Any .) (使用 Mypy reveal_type function 表明 Mypy 将leftright视为Any 。)

What is the correct way to deal with this to stop Mypy complaining?处理此问题以阻止 Mypy 抱怨的正确方法是什么?

I have tested it also without using the cast command.我也没有使用cast命令对其进行了测试。 The Mypy check is passed without any error with the following code: Mypy 检查通过,没有任何错误,代码如下:

import pandas as pd

def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
    return bool(left == right)

(Tested with Mypy 0910.) (使用 Mypy 0910 测试。)

you can cast it as a bool.您可以将其转换为布尔值。

import pandas as pd

def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
    return bool(left == right)

if mypy doesn't like that you can import cast from typing and use that to cast it to a bool.如果 mypy 不喜欢这样,您可以从类型中导入cast并使用它来将其转换为 bool。

import pandas as pd
from typing import cast

def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
    result = bool(left == right)
    return cast(bool, result)

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

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