Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type annotation for function returning a lambda

I’m very fond of the idea of using type annotations in Python. I know how to do such like in this simple example:

def foo(bar : int, lol : int) -> int:
     return bar*lol

But I have no clue of how to do so when my function is going to return a lambda:

def line(slope : float, b : float) -> lambda:
     return lambda x: slope*x + b

This example generates an error, and I wonder what’s the keyword I’m supposed to use for this return type.

Perhaps this doesn’t seem so useful but I want to keep my code consistently annotated and being unable to do so with these type of functions is really bothering me.

Thanks in advance.

like image 979
Maganna Dev Avatar asked Jul 07 '18 16:07

Maganna Dev


People also ask

How do you return a lambda function?

The lambda functions do not need a return statement, they always return a single expression.

What type does lambda return?

The return type of a lambda expression is automatically deduced. You don't have to use the auto keyword unless you specify a trailing-return-type. The trailing-return-type resembles the return-type part of an ordinary function or member function.

How do you type a lambda function?

The syntax of a lambda function is lambda args: expression . You first write the word lambda , then a single space, then a comma separated list of all the arguments, followed by a colon, and then the expression that is the body of the function.

What is lambda function syntax?

Syntax. Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. lambda argument(s): expression. A lambda function evaluates an expression for a given argument.


1 Answers

You can use Callable to type hint the return:

from typing import Callable

def line(slope: float, b : float) -> Callable[[float], float]:
     return lambda x: slope*x + b
like image 155
Carcigenicate Avatar answered Nov 02 '22 11:11

Carcigenicate