8000 add topics about combination with `Self` type · CarliJoy/intersection_examples@b130e68 · GitHub
[go: up one dir, main page]

Skip to content

Commit b130e68

Browse files
committed
add topics about combination with Self type
1 parent bcca491 commit b130e68

File tree

1 file changed

+40
-5
lines changed

1 file changed

+40
-5
lines changed

specification.rst

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,20 +80,31 @@ For example,
8080

8181
::
8282

83-
class LoginRequiredMixin:
83+
class LoginRequiredMixin(AccessMixin):
8484
def dispatch(self, request, *args, **kwargs):
8585
if not request.user.is_authenticated:
86-
...
87-
return super().dispatch(request, *args, **kwargs)
86+
# calling a method of `AccessMixin`
87+
return self.handle_no_permission() # Valid
88+
# calling a method of `View`
89+
return super().dispatch(request, *args, **kwargs) # Invalid
90+
# ^^^^^^^^ Cannot access member "dispatch" for type "AccessMixin"
91+
# Member "dispatch" is unknown
8892

8993
The `LoginRequiredMixin` is designed to be used with the `View` base class which defines the
9094
`dispatch` method.
9195
Intersection types allow expressing that directly via
9296

9397
::
9498

95-
class LoginRequiredMixin:
96-
def dispatch(self: LoginRequiredMixin & View, request, *args, **kwargs): ...
99+
from typing import Self
100+
101+
class LoginRequiredMixin(AccessMixin):
102+
def dispatch(self: Self & View, request, *args, **kwargs):
103+
if not request.user.is_authenticated:
104+
# calling a method of `AccessMixin`
105+
return self.handle_no_permission() # Valid
106+
# calling a method of `View`
107+
return super().dispatch(request, *args, **kwargs) # Valid
97108

98109
Source: https://docs.djangoproject.com/en/3.2/topics/auth/default/#django.contrib.auth.mixins.LoginRequiredMixin
99110

@@ -157,6 +168,30 @@ users could drop the `IterableContainer` class and instead annotate `it` as
157168

158169
Source: https://github.com/python/typing/issues/18
159170

171+
172+
Self
173+
----
174+
175+
PEP-673 introduced `Self`, a simple and intuitive way to annotate methods that return an instance
176+
of their class.
177+
If methods or attributes of intersection types return `Self`-typed values, they should be inferred
178+
as intersection types.
179+
For example,
180+
181+
::
182+
183+
from typing import Self
184+
185+
class Sample: ...
186+
187+
class Mixin:
188+
@property
189+
def me(self) -> Self: ...
190+
191+
a: Sample & Mixin
192+
reveal_type(a.me) # Sample & Mixin
193+
194+
160195
TypedDict
161196
---------
162197

0 commit comments

Comments
 (0)
0