Nepo Znat
Nepo Znat

Reputation: 3280

How to type hint that a function returns another function?

I have the following two functions:

def payment_failed(user: User, charge: Charge, type: str) -> HttpResponse:
    # ... do something here
    return HttpResponse(status=200)


def payment_canceled(*args):
    return payment_failed(*args)

I also want to use type hinting for the payment_canceled function but I'm not sure which version is correct.

Version 1:

def payment_canceled(*args) -> payment_failed:
    return payment_failed(*args)

Version 2:

def payment_canceled(*args) -> HttpResponse:
    return payment_failed(*args)

Upvotes: 2

Views: 909

Answers (1)

chepner
chepner

Reputation: 532268

payment_canceled doesn't return another function; it calls payment_failed and returns whatever it returns. The second is correct:

def payment_canceled(*args) -> HttpResponse:
    return payment_failed(*args)

If you really were returning a function, Callable from the typing module would be appropriate.

from typing import Callable

def payment_canceled(*args) -> Callable[Tuple[Any],HttpResponse]:
    return payment_failed

Upvotes: 7

Related Questions