函数注解 [英] Function annotations

查看:26
本文介绍了函数注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢函数注释,因为它们使我的代码更加清晰.但是我有一个问题:如何注释一个将另一个函数作为参数的函数?还是返回一个?

I really do like function annotations, because they make my code a lot clearer. But I have a question: How do you annotate a function that takes another function as an argument? Or returns one?

def x(f: 'function') -> 'function':
    def wrapper(*args, **kwargs):
        print("{}({}) has been called".format(f.__name__, ", ".join([repr(i) for i in args] + ["{}={}".format(key, value) for key, value in kwargs])))
        return f(*args, **kwargs)
    return wrapper

而且我不想在注释中使用 Function = type(lambda: None) 来使用它.

And I don't want to do Function = type(lambda: None) to use it in annotations.

推荐答案

使用新的 <代码>打字类型提示支持添加到Python 3.5;函数是可调用的,你不需要函数类型,你想要一些可以被调用的东西:

Use the new typing type hinting support added to Python 3.5; functions are callables, you don't need a function type, you want something that can be called:

from typing import Callable, Any

def x(f: Callable[..., Any]) -> Callable[..., Any]:
    def wrapper(*args, **kwargs):
        print("{}({}) has been called".format(f.__name__, ", ".join([repr(i) for i in args] + ["{}={}".format(key, value) for key, value in kwargs])))
        return f(*args, **kwargs)
    return wrapper

上面指定你的 x 接受一个接受任何参数的可调用对象,它的返回类型是 Any,例如无论如何,它是一个通用的可调用对象.x 然后返回一些同样通用的东西.

The above specifies that your x takes a callable object that accepts any arguments, and it's return type is Any, e.g. anything goes, it is a generic callable object. x then returns something that is just as generic.

你可以用 x(f: Callable) ->可调用: 也是;一个普通的 Callable 等价于 Callable[..., Any].你选择哪一个是风格选择,我在这里使用了明确的选项作为我的个人偏好.

You could express this with x(f: Callable) -> Callable: too; a plain Callable is equivalent to Callable[..., Any]. Which one you pick is a style choice, I used the explicit option here as my personal preference.

这篇关于函数注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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