| 1 |
Duck type compatibility |
| 2 |
----------------------- |
| 3 |
|
| 4 |
In Python, certain types are compatible even though they aren't subclasses of |
| 5 |
each other. For example, ``int`` objects are valid whenever ``float`` objects |
| 6 |
are expected. Mypy supports this idiom via *duck type compatibility*. This is |
| 7 |
supported for a small set of built-in types: |
| 8 |
|
| 9 |
* ``int`` is duck type compatible with ``float`` and ``complex``. |
| 10 |
* ``float`` is duck type compatible with ``complex``. |
| 11 |
|
| 12 |
.. note:: |
| 13 |
``bytearray`` and ``memoryview`` were duck type compatible with ``bytes`` |
| 14 |
by default prior to mypy 2.0. This can still be enabled with |
| 15 |
:option:`--no-strict-bytes <mypy --no-strict-bytes>`. |
| 16 |
|
| 17 |
For example, mypy considers an ``int`` object to be valid whenever a |
| 18 |
``float`` object is expected. Thus code like this is nice and clean |
| 19 |
and also behaves as expected: |
| 20 |
|
| 21 |
.. code-block:: python |
| 22 |
|
| 23 |
import math |
| 24 |
|
| 25 |
def degrees_to_radians(degrees: float) -> float: |
| 26 |
return math.pi * degrees / 180 |
| 27 |
|
| 28 |
n = 90 # Inferred type 'int' |
| 29 |
print(degrees_to_radians(n)) # Okay! |
| 30 |
|
| 31 |
You can also often use :ref:`protocol-types` to achieve a similar effect in |
| 32 |
a more principled and extensible fashion. Protocols don't apply to |
| 33 |
cases like ``int`` being compatible with ``float``, since ``float`` is not |
| 34 |
a protocol class but a regular, concrete class, and many standard library |
| 35 |
functions expect concrete instances of ``float`` (or ``int``). |