运算符模块的Python3类型提示

问题描述

如何为应该是运算符的参数编写类型提示?例如,请参见以下功能

import operator
from typing import Dict,Tuple

def func(thresholds: Dict[str,Tuple[operator,float]] = None):
    if thresholds is None:
        thresholds = {"height": (operator.lt,0.7),"width": (operator.gt,0.1)}
    pass

当我尝试运行代码时,我得到:

TypeError: Tuple[t0,t1,...]: each t must be a type. Got <module 'operator' from ...>.

编辑:我意识到运算符是一个模块,而不是类型,而我正在寻找的参数是该模块中的函数。我正在尝试查看是否有任何方法可以让用户知道我希望将运算符用作参数。是唯一解释文档字符串的方法吗?

解决方法

operator是一个模块,而不是类或类型。您要做的是创建一个可以满足传递给func的函数的类型提示。如果我们要从头开始编写operator.lt,它可能看起来像这样:

from numbers import Number

def le(a: Number,b: Number) -> bool:
    ...

使用Callable类型,我们可以这样写:

Callable[[Number,Number],bool]

将其放在一起,您将得到以下内容:

import operator
from typing import Dict,Tuple,Callable,Optional
from numbers import Number


Operator = Callable[[Number,bool]
OperatorDict = Dict[str,Tuple[Operator,float]]


def func(thresholds: Optional[OperatorDict] = None) -> None:
    if thresholds is None:
        thresholds = {"height": (operator.lt,0.7),"width": (operator.gt,0.1)}
    pass