@@ -193,10 +193,11 @@ Generic methods and generic self
193
193
********************************
194
194
195
195
You can also define generic methods — just use a type variable in the
196
- method signature that is different from class type variables. In particular,
197
- ``self `` may also be generic, allowing a method to return the most precise
198
- type known at the point of access. In this way, for example, you can typecheck
199
- chaining of setter methods:
196
+ method signature that is different from class type variables. In
197
+ particular, the ``self `` argument may also be generic, allowing a
198
+ method to return the most precise type known at the point of access.
199
+ In this way, for example, you can type check a chain of setter
200
+ methods:
200
201
201
202
.. code-block :: python
202
203
@@ -222,7 +223,9 @@ chaining of setter methods:
222
223
circle: Circle = Circle().set_scale(0.5 ).set_radius(2.7 )
223
224
square: Square = Square().set_scale(0.5 ).set_width(3.2 )
224
225
225
- Without using generic ``self ``, the last two lines could not be type-checked properly.
226
+ Without using generic ``self ``, the last two lines could not be type
227
+ checked properly, since the return type of ``set_scale `` would be
228
+ ``Shape ``, which doesn't define ``set_radius `` or ``set_width ``.
226
229
227
230
Other uses are factory methods, such as copy and deserialization.
228
231
For class methods, you can also define generic ``cls ``, using :py:class: `Type[T] <typing.Type> `:
@@ -255,16 +258,18 @@ In the latter case, you must implement this method in all future subclasses.
255
258
Note also that mypy cannot always verify that the implementation of a copy
256
259
or a deserialization method returns the actual type of self. Therefore
257
260
you may need to silence mypy inside these methods (but not at the call site),
258
- possibly by making use of the ``Any `` type.
261
+ possibly by making use of the ``Any `` type or a `` # type: ignore `` comment .
259
262
260
- Note that this feature may accept some unsafe code for the purpose of
261
- *practicality *. For example:
263
+ Note that mypy lets you use generic self types in certain unsafe ways
264
+ in order to support common idioms. For example, using a generic
265
+ self type in an argument type is accepted even though it's unsafe:
262
266
263
267
.. code-block :: python
264
268
265
269
from typing import TypeVar
266
270
267
271
T = TypeVar(" T" )
272
+
268
273
class Base :
269
274
def compare (self : T, other : T) -> bool :
270
275
return False
@@ -273,25 +278,27 @@ Note that this feature may accept some unsafe code for the purpose of
273
278
def __init__ (self , x : int ) -> None :
274
279
self .x = x
275
280
276
- # This is unsafe (see below), but allowed because it is
277
- # a common pattern, and rarely causes issues in practice.
281
+ # This is unsafe (see below) but allowed because it's
282
+ # a common pattern and rarely causes issues in practice.
278
283
def compare (self , other : Sub) -> bool :
279
284
return self .x > other.x
280
285
281
286
b: Base = Sub(42 )
282
287
b.compare(Base()) # Runtime error here: 'Base' object has no attribute 'x'
283
288
284
- For some advanced uses of self- types see :ref: `additional examples <advanced_self >`.
289
+ For some advanced uses of self types, see :ref: `additional examples <advanced_self >`.
285
290
286
291
Automatic self types using typing.Self
287
292
**************************************
288
293
289
- The patterns described above are quite common, so there is a syntactic sugar
290
- for them introduced in :pep: `673 `. Instead of defining a type variable and
291
- using an explicit ``self `` annotation, you can import a magic type ``typing.Self ``
292
- that is automatically transformed into a type variable with an upper bound of
293
- current class, and you don't need an annotation for ``self `` (or ``cls `` for
294
- class methods). The above example can thus be rewritten as:
294
+ Since the patterns described above are quite common, mypy supports a
295
+ simpler syntax, introduced in :pep: `673 `, to make them easier to use.
296
+ Instead of defining a type variable and using an explicit annotation
297
+ for ``self ``, you can import the special type ``typing.Self `` that is
298
+ automatically transformed into a type variable with the current class
299
+ as the upper bound, and you don't need an annotation for ``self `` (or
300
+ ``cls `` in class methods). The example from the previous section can
301
+ be made simpler by using ``Self ``:
295
302
296
303
.. code-block :: python
297
304
@@ -312,13 +319,13 @@ class methods). The above example can thus be rewritten as:
312
319
313
320
a, b = SuperFriend.make_pair()
314
321
315
- This is more compact than using explicit type variables, plus additionally
316
- you can use ``Self `` in attribute annotations, not just in methods.
322
+ This is more compact than using explicit type variables. Also, you can
323
+ use ``Self `` in attribute annotations in addition to methods.
317
324
318
325
.. note ::
319
326
320
- To use this feature on versions of Python before 3.11, you will need to
321
- import ``Self `` from ``typing_extensions `` version 4.0 or newer.
327
+ To use this feature on Python versions earlier than 3.11, you will need to
328
+ import ``Self `` from ``typing_extensions `` ( version 4.0 or newer) .
322
329
323
330
.. _variance-of-generics :
324
331
@@ -911,7 +918,7 @@ defeating the purpose of using aliases. Example:
911
918
912
919
OIntVec = Optional[Vec[int ]]
913
920
914
- Using type variable bounds or values in generic aliases, has the same effect
921
+ Using type variable bounds or values in generic aliases has the same effect
915
922
as in generic classes/functions.
916
923
917
924
0 commit comments