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

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

问题描述

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

I have a function that can only return a, b or c, all of them are of type T. And 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

那是正确的吗?

我知道我可以做到

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.

推荐答案

不能单独使用类型提示来指定函数仅返回类型值的子集.顾名思义,类型提示完全是关于类型而不是值.

You can't specify that your function returns only a subset of a type's values using type hinting alone. As the name implies, type hinting is all about types not values.

但是,您可以创建一个新的enum.Enum子类型,该子类型仅具有要返回的值,并在函数中使用它.然后,您可以键入提示您将返回枚举类型.

However, you can create a new enum.Enum subtype that only has the values you're going to return and use it in the function. Then you can type hint that you're returning the enum type.

import enum

class cmp_results(enum.IntEnum):
    less = -1
    equal = 0
    greater = 1

def my_cmp_function(x, y) -> cmp_results:
    if x < y: return cmp_results.less
    elif x == y: return cmp_results.equal
    else: return cmp_results.greater

这可能是过大的杀伤力.仅暗示int作为返回类型(并记录特定值)可能就足够了.

This may be overkill. Just hinting int as the return type (and documenting the specific values) is probably good enough.

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

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