I defined an Enum like this:
from enum import Enum
from typing import Self
class Letter(Enum):
A = "A"
B = "B"
C = "C"
@property
def neighbors(self) -> list[Self]:
match self:
case self.A:
return [self.B]
case self.B:
return [self.A, self.C]
case self.C:
return [self.B]
case _:
raise ValueError
print(Letter.A.neighbors)
print(type(Letter.A.neighbors))
Visual Studio Code shows me the following error message:
Pylance Error: Expression cannot be assigned to return type ...
The code runs without any problem.
Is there actually an issue with the code, with Pylance or with the Visual Studio Code editor?
In any case, how can I get rid of this error message?
Enum @property method return type Self shows a Pylance error in Visual Studio Code.
Enum
classes (with members) are final, even at runtime, so there is no need to use Self
. Use Letter
directly:
(playground: Pyright)
from enum import Enum
class Letter(Enum):
...
@property
def neighbors(self) -> list['Letter']:
match self:
case self.A: # Or `Letter.A`
return [self.B] # Or `Letter.B`
...
The behaviour in question is said to be as designed:
The
Self
type is effectively a type variable that has an upper bound of the containing class. It is not the same as the class itself.
Also, you can remove the last, wildcard branch:
case _:
# ~
# Pyright will raise an error here since the checking
# done by other branches are already exhaustive.
raise ValueError