我有如下代码:

from typing import Callable


def decorate(func: Callable[[str], None]) -> Callable[[str], None]:
    return func


@decorate
def do_something(some_str: str = 'Hello world') -> None:
    print(some_str)


if __name__ == '__main__':
    do_something()

运行mypy时,它会在最后一行报告以下错误:

错误:"do\u something"[调用参数]的参数太少

如何修复此错误(不将返回类型decorate更改为Callable[..., None])?

推荐答案

使用TypeVar表示接收到的any Callable的输入和返回类型等效.由于Callable个类型包含整个签名,因此类型判断器也可以推断位置/可选/关键字参数.

from typing import Callable, TypeVar

# A type variable that can represent any Callable type
C = TypeVar("C", bound=Callable)

# The input Callable type defines the output Callable type as well
def decorate(func: C) -> C:
    return func

如果decorate只能处理可能需要字符串的可调用项,则相应地调整bound.

# A type variable that can represent any Callable type that takes a string
C = TypeVar("C", bound=Callable[[str], None])

值得注意的是,接受str or using a default的可调用函数仍然满足Callable[[str], None],因为它可以用str参数调用.

Python相关问答推荐

Django管理面板显示字段最大长度而不是字段名称

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

使用miniconda创建环境的问题

从dict的列中分钟

使用@ guardlasses. guardlass和注释的Python继承

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

Odoo 16使用NTFS使字段只读

根据列值添加时区

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

Python全局变量递归得到不同的结果

语法错误:文档. evaluate:表达式不是合法表达式

根据Pandas中带条件的两个列的值创建新列

提取数组每行的非零元素

如何使用pytest在traceback中找到特定的异常

为什么Visual Studio Code说我的代码在使用Pandas concat函数后无法访问?

在pandas中,如何在由两列加上一个值列组成的枢轴期间或之后可靠地设置多级列的索引顺序,

在不中断格式的情况下在文件的特定部分插入XML标签

如何让PYTHON上的Selify连接到现有的Firefox实例-我无法连接到Marionette端口

pyspark where子句可以在不存在的列上工作

使用OpenPYXL切换图表上的行/列