【问题标题】:Declare input parameters for function-type in parameter declaration using typing [duplicate]使用类型 [重复] 在参数声明中声明函数类型的输入参数
【发布时间】:2026-02-22 23:20:06
【问题描述】:

上下文

假设一个函数接受这样的函数:

def some_func(
        parameter_1: str
        , func: function
    ):
    pass

可以看出func应该是一个传递给some_func的函数。

无论如何,func 应该是一个接受特定参数类型的函数:

def func(
        specific_parameter_of_type_string: str
    ):
    pass

问题

我如何在some_func() 中声明参数func 应该是一个接受str 的函数?

我查看了typing-module,但没有找到我的问题的解决方案。反正我觉得应该是可以解决的……

我假设的结果类似于这样:

import typing

def some_func(
        parameter_1: str
        , func: typing.Function[str] # Example! This does not exist in typing
    ):
    pass

【问题讨论】:

  • @not_speshal:对不起,但这不是解决这个问题的方法——强制转换与类型提示完全不同。
  • "func 应该是一个接受特定参数类型的函数"
  • 您在寻找Callable吗?
  • @not_speshal: 没错,这不是通过强制转换而是通过键入来声明的:)
  • @MisterMiyagi:是的,我是 :) 在你写的那一刻也遇到了这个:D

标签: python type-hinting typing


【解决方案1】:

仔细阅读打字文档我发现函数实际上被称为typing.Callables,可以阅读here

因此,这可用于指定返回类型和输入参数:

可调用[[Arg1Type, Arg2Type], ReturnType]

那么解决办法是:

import typing

def some_func(
        parameter_1: str
        , func: typing.Callable[[str], None]
    ):
    pass

【讨论】: