@@ -262,10 +262,11 @@ Generic methods and generic self
262
262
********************************
263
263
264
264
You can also define generic methods — just use a type variable in the
265
- method signature that is different from class type variables. In particular,
266
- ``self `` may also be generic, allowing a method to return the most precise
267
- type known at the point of access. In this way, for example, you can typecheck
268
- chaining of setter methods:
265
+ method signature that is different from class type variables. In
266
+ particular, the ``self `` argument may also be generic, allowing a
267
+ method to return the most precise type known at the point of access.
268
+ In this way, for example, you can type check a chain of setter
269
+ methods:
269
270
270
271
.. code-block :: python
271
272
@@ -291,7 +292,9 @@ chaining of setter methods:
291
292
circle: Circle = Circle().set_scale(0.5 ).set_radius(2.7 )
292
293
square: Square = Square().set_scale(0.5 ).set_width(3.2 )
293
294
294
- Without using generic ``self ``, the last two lines could not be type-checked properly.
295
+ Without using generic ``self ``, the last two lines could not be type
296
+ checked properly, since the return type of ``set_scale `` would be
297
+ ``Shape ``, which doesn't define ``set_radius `` or ``set_width ``.
295
298
296
299
Other uses are factory methods, such as copy and deserialization.
297
300
For class methods, you can also define generic ``cls ``, using :py:class: `Type[T] <typing.Type> `:
@@ -324,16 +327,18 @@ In the latter case, you must implement this method in all future subclasses.
324
327
Note also that mypy cannot always verify that the implementation of a copy
325
328
or a deserialization method returns the actual type of self. Therefore
326
329
you may need to silence mypy inside these methods (but not at the call site),
327
- possibly by making use of the ``Any `` type.
330
+ possibly by making use of the ``Any `` type or a `` # type: ignore `` comment .
328
331
329
- Note that this feature may accept some unsafe code for the purpose of
330
- *practicality *. For example:
332
+ Note that mypy lets you use generic self types in certain unsafe ways
333
+ in order to support common idioms. For example, using a generic
334
+ self type in an argument type is accepted even though it's unsafe:
331
335
332
336
.. code-block :: python
333
337
334
338
from typing import TypeVar
335
339
336
340
T = TypeVar(" T" )
341
+
337
342
class Base :
338
343
def compare (self : T, other : T) -> bool :
339
344
return False
@@ -342,25 +347,27 @@ Note that this feature may accept some unsafe code for the purpose of
342
347
def __init__ (self , x : int ) -> None :
343
348
self .x = x
344
349
345
- # This is unsafe (see below), but allowed because it is
346
- # a common pattern, and rarely causes issues in practice.
350
+ # This is unsafe (see below) but allowed because it's
351
+ # a common pattern and rarely causes issues in practice.
347
352
def compare (self , other : Sub) -> bool :
348
353
return self .x > other.x
349
354
350
355
b: Base = Sub(42 )
351
356
b.compare(Base()) # Runtime error here: 'Base' object has no attribute 'x'
352
357
353
- For some advanced uses of self- types see :ref: `additional examples <advanced_self >`.
358
+ For some advanced uses of self types, see :ref: `additional examples <advanced_self >`.
354
359
355
360
Automatic self types using typing.Self
356
361
**************************************
357
362
358
- The patterns described above are quite common, so there is a syntactic sugar
359
- for them introduced in :pep: `673 `. Instead of defining a type variable and
360
- using an explicit ``self `` annotation, you can import a magic type ``typing.Self ``
361
- that is automatically transformed into a type variable with an upper bound of
362
- current class, and you don't need an annotation for ``self `` (or ``cls `` for
363
- class methods). The above example can thus be rewritten as:
363
+ Since the patterns described above are quite common, mypy supports a
364
+ simpler syntax, introduced in :pep: `673 `, to make them easier to use.
365
+ Instead of defining a type variable and using an explicit annotation
366
+ for ``self ``, you can import the special type ``typing.Self `` that is
367
+ automatically transformed into a type variable with the current class
368
+ as the upper bound, and you don't need an annotation for ``self `` (or
369
+ ``cls `` in class methods). The example from the previous section can
370
+ be made simpler by using ``Self ``:
364
371
365
372
.. code-block :: python
366
373
@@ -381,13 +388,13 @@ class methods). The above example can thus be rewritten as:
381
388
382
389
a, b = SuperFriend.make_pair()
383
390
384
- This is more compact than using explicit type variables, plus additionally
385
- you can use ``Self `` in attribute annotations, not just in methods.
391
+ This is more compact than using explicit type variables. Also, you can
392
+ use ``Self `` in attribute annotations in addition to methods.
386
393
387
394
.. note ::
388
395
389
- To use this feature on versions of Python before 3.11, you will need to
390
- import ``Self `` from ``typing_extensions `` version 4.0 or newer.
396
+ To use this feature on Python versions earlier than 3.11, you will need to
397
+ import ``Self `` from ``typing_extensions `` ( version 4.0 or newer) .
391
398
392
399
.. _variance-of-generics :
393
400
@@ -916,5 +923,5 @@ defeating the purpose of using aliases. Example:
916
923
917
924
OIntVec = Optional[Vec[int ]]
918
925
919
- Using type variable bounds or values in generic aliases, has the same effect
926
+ Using type variable bounds or values in generic aliases has the same effect
920
927
as in generic classes/functions.
0 commit comments