Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write type hints for a function returning itself?

from typing import Callable


def f() -> Callable:
    return f

How to explicitly define f's type? like Callable[[], Callable]

I think it is slightly like a linked list, but I can't implement it.

from typing import Union


class Node:
    def __init__(self, val):
        self.val = val
        self.next: Union[Node, None] = None
like image 281
AsukaMinato Avatar asked Sep 16 '25 21:09

AsukaMinato


1 Answers

I think @chepner's answer is great. If you really do want to express this as a recursive Callable type, then you could restructure the function as a callable class and do something like this:

from __future__ import annotations


class F:
    def __call__(self) -> F:
        return self


f = F()

You can test this with mypy to see that it maintains its type on future calls:

g = f()
h = g(1)  # Too many arguments for "__call__" of "F"
i = h()
j = i(2)  # Too many arguments for "__call__" of "F"
k = j()
like image 100
flakes Avatar answered Sep 19 '25 09:09

flakes