PEP 673: forbid Self in type aliases. (#2194)
Thanks to Eric Traut who tested all the code examples in Pyright and raised implementation concerns about ``Self`` type in aliases. I ran into implementation issues in Pyre too. This is because Pyre preprocesses things like ``Self`` in an early phase and does alias resolution in a later phase. Mixing the two would lead to a lot of hacks.
This commit is contained in:
parent
b999554240
commit
9c60e96f0f
23
pep-0673.rst
23
pep-0673.rst
|
@ -605,11 +605,6 @@ The following uses of ``Self`` are accepted:
|
|||
# Accepted (treated as an @property returning the Callable type)
|
||||
bar: Callable[[Self], int] = foo
|
||||
|
||||
TupleSelf = Tuple[Self, Self]
|
||||
class Alias:
|
||||
def return_tuple(self) -> TupleSelf:
|
||||
return (self, self)
|
||||
|
||||
class HasNestedFunction:
|
||||
x: int = 42
|
||||
|
||||
|
@ -660,6 +655,20 @@ The following uses of ``Self`` are rejected.
|
|||
|
||||
class Baz(Foo[Self]): ... # Rejected
|
||||
|
||||
We reject type aliases containing ``Self``. Supporting ``Self``
|
||||
outside class definitions can require a lot of special-handling in
|
||||
type checkers. Given that it also goes against the rest of the PEP to
|
||||
use ``Self`` outside a class definition, we believe the added
|
||||
convenience of aliases is not worth it:
|
||||
|
||||
::
|
||||
|
||||
TupleSelf = Tuple[Self, Self] # Rejected
|
||||
|
||||
class Alias:
|
||||
def return_tuple(self) -> TupleSelf: # Rejected
|
||||
return (self, self)
|
||||
|
||||
Note that we reject ``Self`` in staticmethods. ``Self`` does not add much
|
||||
value since there is no ``self`` or ``cls`` to return. The only possible use
|
||||
cases would be to return a parameter itself or some element from a container
|
||||
|
@ -781,8 +790,8 @@ Other languages have similar ways to express the type of the enclosing class:
|
|||
|
||||
Thanks to the following people for their feedback on the PEP:
|
||||
|
||||
Jia Chen, Rebecca Chen, Sergei Lebedev, Kaylynn Morgan, Tuomas Suutari, Alex
|
||||
Waygood, Shannon Zhu, and Никита Соболев
|
||||
Jia Chen, Rebecca Chen, Sergei Lebedev, Kaylynn Morgan, Tuomas
|
||||
Suutari, Eric Traut, Alex Waygood, Shannon Zhu, and Никита Соболев
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
|
Loading…
Reference in New Issue