如何在类型提示中指定函数类型? [英] How can I specify the function type in my type hints?

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

问题描述

我想在我当前的 Python 3.5 项目中使用类型提示.我的函数应该接收一个函数作为参数.

I want to use type hints in my current Python 3.5 project. My function should receive a function as parameter.

如何在类型提示中指定类型函数?

import typing

def my_function(name:typing.AnyStr, func: typing.Function) -> None:
    # However, typing.Function does not exist.
    # How can I specify the type function for the parameter `func`?

    # do some processing
    pass

我检查了 PEP 483,但找不到函数类型提示

I checked PEP 483, but could not find a function type hint there.

推荐答案

As @jonrsharpe 在评论中指出,这可以通过 typing.Callable:

As @jonrsharpe noted in a comment, this can be done with typing.Callable:

from typing import AnyStr, Callable

def my_function(name: AnyStr, func: Callable) -> None:

问题是,Callable 本身被翻译成 Callable[..., Any],意思是:

Issue is, Callable on it's own is translated to Callable[..., Any] which means:

一个可调用对象接受任意数量/类型的参数并返回任意类型的值.在大多数情况下,这不是您想要的,因为您将允许传递几乎任何函数.您还希望提示函数参数和返回类型.

A callable takes any number of/type of arguments and returns a value of any type. In most cases, this isn't what you want since you'll allow pretty much any function to be passed. You want the function parameters and return types to be hinted too.

这就是为什么 typing 中的许多 types 已经被重载以支持表示这些额外类型的子脚本.因此,例如,如果您有一个函数 sum,它接受两个 int 并返回一个 int:

That's why many types in typing have been overloaded to support sub-scripting which denotes these extra types. So if, for example, you had a function sum that takes two ints and returns an int:

def sum(a: int, b: int) -> int: return a+b

你的注释是:

Callable[[int, int], int]

即参数在外部订阅中被下标,返回类型作为外部订阅中的第二个元素.一般:

that is, the parameters are sub-scripted in the outer subscription with the return type as the second element in the outer subscription. In general:

Callable[[ParamType1, ParamType2, .., ParamTypeN], ReturnType]

这篇关于如何在类型提示中指定函数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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