GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||
GeezerVison is showing github.com — Supporting `Self` for Free Functions? · python/typing · Discussion #2294
Supporting
|
|
Currently, I noticed that typing a function that returns itself requires recursive callable aliases, for example: from typing import TypeAlias from collections.abc import Callable SelfFunc: TypeAlias = Callable[..., "SelfFunc"] def f() -> SelfFunc: return f Would it make sense to allow: from typing import Self def f() -> Self: return f for standalone functions? This seems more readable and directly expresses intent, but I’m not sure whether there are ambiguity or implementation issues with extending Are there reasons this should or should not be supported? |
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
There was an error while loading. Please reload this page.
|
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? |
There was an error while loading. Please reload this page.
|
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. |
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
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 |
There was an error while loading. Please reload this page.
|
I didn’t think about using a protocol with What I was mainly thinking about was annotating the function itself, especially for nested/self-referential functions like: def outer(): def inner() -> ???: return inner The protocol approach does work, but it feels a little verbose for something as simple as “this function returns itself”. I do get the concern about adding another special case to the type system though, especially for something pretty niche. |