为仅返回一组特定值的函数键入提示 [英] Type hint for a function that returns only a specific set of values

查看:26
本文介绍了为仅返回一组特定值的函数键入提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数只能返回abc,它们都是T类型的代码>.我想在签名中包含这个事实,因为它们在函数的上下文中具有特殊的含义.我该怎么做?

I have a function that can only return a, b or c, all of them are of type T. I want to include this fact in the signature because of the special meaning they carry in the context of the function. How do I do that?

目前,我使用这个

def fun(...) -> "a or b or c":
    #briefly explain the meaning of a, b and c in its docstring

这是正确的吗?

我知道我可以做到这一点

I know that I can do this

def fun(...) -> T:
    # briefly explain the meaning of a, b and c in its docstring

但正如我所说,我想在签名中表示函数只返回那些特定的值.

but as I said, I want to express in the signature that the function only returns those specific values.

推荐答案

你可以使用 文字类型.

from typing_extensions import Literal
# from typing import Literal  # Python 3.8 or higher

def fun(b: int) -> Literal["a", "b", "c"]:
    if b == 0:
        return "a"
    if b == 1:
        return "b"
    return "d"

mypy 能够将 return "d" 检测为无效语句:

mypy is able to detect the return "d" as a invalid statement:

error: Incompatible return value type (got "Literal['d']",
expected "Union[Literal['a'], Literal['b'], Literal['c']]")

Python 3.8

感谢 PEP 586文字代码>默认已经包含 Python 3.8 打字模块.

Python 3.8

Thanks to the PEP 586, the Literal is already included by default in the Python 3.8 typing module.

这篇关于为仅返回一组特定值的函数键入提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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