Function annotations

安稳与你 提交于 2019-12-24 16:00:21

问题


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

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


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/36726053/function-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!