功能注释 [英] Function annotations
问题描述
我真的很喜欢函数注释,因为它们使我的代码更加清晰.但是我有一个问题:如何注释以另一个函数作为参数的函数?还是返回一个?
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中添加了code> typing 类型提示支持;函数是 callables ,您不需要函数类型,而是需要可以调用的东西:
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屋!