简体   繁体   English

是否可以使用布尔返回函数作为类型提示?

[英]Is it possible to use a boolean-returning function as a type hint?

Below are two examples of functions having some type hints:以下是具有一些类型提示的函数的两个示例:

def sum_dem_digits(digits:str) -> int:
    return sum(int(d) for d in digits)

def do_stuff(x:int):
    lizzard = ["eyes", "nose", "body", "tail"]
    return lizzard[x]

Is there some way to set an arbitrary boolean-returning function to be the type hint?有没有办法将任意布尔返回函数设置为类型提示?

import string

def numeric_string(chs:str) -> bool:
    """
        BAD:  "ANACONDA, RATTLESNAKE, SIDEWINDER"
        BAD:  "WHAT I HAD FOR LUNCH"
        GOOD: "1234"
        GOOD: "99"
    """
    return all([ch in string.digits for ch in chs])

def sum_dem_digits(digits:numeric_string) -> int:
    return sum(int(d) for d in digits)

#######################################################################

def do_stuff_helper(x:int):
    return (0 <= x) and (x <= 3)

def do_stuff(x:do_stuff_helper):
    lizzard = ["eyes", "nose", "body", "tail"]
    return lizzard[x]

The answer isn't quite a straightforward yes or no.答案不是一个简单的“是”或“否”。

Arbitrary functions are not valid static types.任意函数不是有效的静态类型。 They are technically legal annotations, because you can use any object as an annotation and Python won't care, but anything that does type analysis with type hints will see this as an error.它们在技术上是合法的注解,因为你可以使用任何对象作为注解并且 Python 不会在意,但是任何使用类型提示进行类型分析的东西都会将此视为错误。

More importantly, why are you doing this?更重要的是,你为什么要这样做? If you were hoping that tools like mypy would be able to check whether inputs pass your function, then that's hopeless.如果您希望 mypy 之类的工具能够检查输入是否通过您的函数,那么这是没有希望的。 mypy is a static tool, and running your function would be a runtime thing. mypy 是一个静态工具,运行你的函数将是一个运行时的事情。 mypy can't see runtime argument values, or figure out what running do_stuff_helper on those values would do. mypy 看不到运行时参数值,也看不到在这些值上运行do_stuff_helper会做什么。

If you want to build your own tool that performs runtime constraint checking based on constraint functions supplied as type annotations, then sure, you can do that.如果您想构建自己的工具,该工具基于作为类型注释提供的约束函数执行运行时约束检查,那么当然,您可以这样做。 Ideally, you'd use typing.Annotated to supply your constraint functions in a way that doesn't interfere with type hints:理想情况下,您会使用typing.Annotated以不干扰类型提示的方式提供约束功能:

class Constraint:
    def __init__(self, constraint_function):
        self.constraint_function = constraint_function

@some_checker_decorator_you_write
def do_stuff(x: Annotated[int, Constraint(do_stuff_helper)]):
    ...

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

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