从带mypy注释的python函数返回None,多种返回类型 [英] Return None from python function annotated with mypy, multiple return types

查看:129
本文介绍了从带mypy注释的python函数返回None,多种返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自打字稿背景.我正在将静态类型检查引入到我正在研究的python项目中(使用mypy).

I come from a Typescript background. I'm bringing static type checking into a python project I'm working on (using mypy).

在Typescript中,从带有注释以返回其他内容(即字符串)的函数中返回null是有效的:

In Typescript, it is valid to return null from a function that is annotated to return something else, i.e. a string:

function test(flag: boolean): string {
    if(flag) {
        return 'success';
    } else {
        return null;
    }
}

注释函数具有多种可能的返回类型(即字符串或布尔值)也是有效的:

It is also valid to annotate your function to have multiple potential return types, i.e. string or boolean:

function test(flag: boolean): string | boolean {
    if(flag) {
        return 'success';
    } else {
        return false;
    }
}

但是,在使用mypy的python中,我不允许从带有注释以返回 str 的函数中返回None.

But, in python using mypy, I'm disallowed from returning None from a function that is annotated to return str.

def test(flag: bool) -> str:
    if flag:
        return 'success'
    else:
        return None
        # [mypy] error:Incompatible return value type (got "None", expected "str")

此外,我看不到注释多种返回类型的方法,即 str |没有.

Furthermore, I don't see a way to annotate multiple return types, i.e. str | None.

我应该如何使用mypy处理类似的事情?从错误状态返回None的函数遍布我的代码库.

How should I approach something like this using mypy? Functions that return None from the error state are all over my codebase.

推荐答案

好吧,感谢mypy gitter上的@zsol,我发现文档中缺少的内容!

Okay, I found what I was missing in the documentation thanks to @zsol on the mypy gitter!

mypy的两个有用功能是Optional和Union类型,可以从python的输入模块中导入它们.此处的文档.

Two helpful mypy features are the Optional and Union types that can be imported from python's typing module. Documentation here.

如果要注释的是,该函数除主要类型外还可能返回None,例如 str ,使用 Optional :

If you want to annotate that the function can potentially return None in addition to the primary type, e.g. str, use Optional:

from typing import Optional

def test(flag: bool) -> Optional[str]:
    if flag:
        return 'success'
    else:
        return None

如果要注释该函数可能返回多个类型,例如 str |bool ,使用 Union :

If you want to annotate that the function can potentially return multiple types, e.g. str | bool, use Union:

from typing import Union

def test(flag: bool) -> Union[str, bool]:
    if flag:
        return 'success'
    else:
        return False

这篇关于从带mypy注释的python函数返回None,多种返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆