Scoped alias with Self #1547
Unanswered
benoitLemoine
asked this question in
Q&A
Replies: 1 comment 1 reply
-
You can think of class Bar(Generic[T]):
MyAlias1: TypeAlias = list[T] # Not allowed because T is a TypeVar bound to the class scope
MyAlias2: TypeAlias = list[Self] # Similarly not allowed because Self is a TypeVar bound to the class scope If you want to define a generic type alias within your class, it needs to use its own type variable. Here's a modified version of your code sample that shows how this might work. from typing import Callable, Self, TypeVar, TypeAlias
T = TypeVar("T")
class Foo:
VisitorFn: TypeAlias = Callable[[T], "Foo"]
_visitors: dict[str, VisitorFn] = {}
def __init_subclass__(cls) -> None:
cls._visitors = {}
@classmethod
def register(cls, name: str) -> Callable[[VisitorFn[Self]], VisitorFn[Self]]:
def inner_register(fn: Foo.VisitorFn[Self]) -> Foo.VisitorFn[Self]:
cls._visitors[name] = fn
return fn
return inner_register
@classmethod
def visitors(cls) -> dict[str, VisitorFn[Self]]:
return cls._visitors Or if you're using Python 3.12, you can use the new PEP 695 syntax: class Foo:
type VisitorFn[T] = Callable[[T], "Foo"]
... |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Upgrading to Python3.11 recently, I gave
Self
a try. I defined a scoped alias using Self (see code snippet).With python on version
3.11.7
and mypy on1.7.1
, mypy gave me the following error :So I took a look to the PEP defining
Self
(https://peps.python.org/pep-0673/), but aside of forbidding all aliases containingSelf
, I found no reason to prevent scoped aliases usingSelf
.Is there a reason for preventing such case or is it a side effect of banning aliases with
Self
?I do some search on similar discussions, but I found nothing related (#1526 is close but not quite the same).
Here is the code snippet
Beta Was this translation helpful? Give feedback.
All reactions