From 9c60e96f0f21bc180310f35d5d06e9c8281096d9 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 16 Dec 2021 06:41:11 -0800 Subject: [PATCH] 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. --- pep-0673.rst | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/pep-0673.rst b/pep-0673.rst index 7069fc193..3fa88733e 100644 --- a/pep-0673.rst +++ b/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 =========