功能注释

时间:2016-04-19 17:58:56

标签: python python-3.x annotations type-hinting

我确实喜欢功能注释,因为它们使我的代码更加清晰。 但我有一个问题:你如何注释一个以另一个函数作为参数的函数?或者返回一个?

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)在注释中使用它。

1 个答案:

答案 0 :(得分:3)

使用添加到Python 3.5的新typing type hinting support;函数是 callables ,你不需要函数类型,你想要一些可以调用的东西:

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。什么都行,它是一个通用的可调用对象。 x(f: Callable) -> Callable:然后返回一些通用的东西。

你也可以用Callable来表达这个;普通Callable[..., Any]相当于{ "state": "open", "settings": { "index": { "http": { "cors": { "allow-credentials": "true", "enabled": "true", "allow-origin": "*" } }, "creation_date": "1461087830891", "number_of_shards": "5", "number_of_replicas": "1", "version": { "created": "1070499" }, "uuid": "2JeIgB7IRs6_DzEb6PLx-w" } }, "mappings": { "tx": { "properties": { "next": { "format": "dateOptionalTime", "type": "date" }, "eid": { "index": "not_analyzed", "type": "string" }, "95percent_time": { "type": "double" }, "total_count": { "type": "long" }, "failure_count": { "type": "long" }, "pool_id": { "type": "long" }, "pool_name": { "index": "not_analyzed", "type": "string" }, "failure_rate": { "type": "double" }, "report_time": { "format": "dateOptionalTime", "type": "date" }, "txn_type": { "index": "not_analyzed", "type": "string" }, "status_default": { "type": "long" }, "txn_name": { "index": "not_analyzed", "type": "string" }, "frequency_type": { "index": "not_analyzed", "type": "string" }, "status_2": { "type": "long" }, "status_1": { "type": "long" }, "avg_time": { "type": "double" }, "datacenter_id": { "type": "long" }, "datacenter_name": { "index": "not_analyzed", "type": "string" }, "server_type": { "type": "string" } } } }, "aliases": [ ] } 。你选择哪一个是风格选择,我在这里使用显式选项作为我个人的偏好。