CodenameLambda
CodenameLambda

Reputation: 1496

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

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

Upvotes: 1

Views: 183

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124238

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.

Upvotes: 3

Related Questions