Supporting Self for Free Functions?
#2294
-
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
|
This would require adding a special case to the type system. We generally only add special cases for things that are very common and useful, and I'm not sure "functions returning themselves" fall in that category. What is the use case? |
Beta Was this translation helpful? Give feedback.
-
|
That's fair. I don't think this is a critical missing feature, but I was wondering whether the readability and expressiveness benefits could justify it. Right now, recursive callable aliases work, but they feel indirect for the specific case of a function returning itself: from typing import TypeAlias
from collections.abc import Callable
SelfFunc: TypeAlias = Callable[..., "SelfFunc"]whereas Potential use cases I thought of were:
Though I agree these may be too niche to justify special handling in the type system. |
Beta Was this translation helpful? Give feedback.
-
|
Would a callback protocol do the trick? from typing import Protocol, Self
class F(Protocol):
def __call__(self, /) -> Self: ...
def factory() -> F:
def f(): return f
return f |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.

Would a callback protocol do the trick?