| 1 |
Static Type Checking |
| 2 |
-------------------- |
| 3 |
|
| 4 |
Crochet comes with type hints for Python 3.6+. However, due to current |
| 5 |
limitations in ``Callable`` generic construction (see |
| 6 |
`PEP 612 — Parameter Specification Variables`_), the arguments of a call to |
| 7 |
a ``@run_in_reactor``-decorated function or method cannot be checked without |
| 8 |
giving type checkers some special help. Crochet ships with a plugin which |
| 9 |
fills this role when the ``mypy`` static type checker is used. It resides in |
| 10 |
``crochet.mypy`` and must be configured as described in |
| 11 |
`Configuring mypy to use plugins`_. For example, in a ``mypy.ini`` |
| 12 |
configuration file:: |
| 13 |
|
| 14 |
[mypy] |
| 15 |
plugins = crochet.mypy |
| 16 |
|
| 17 |
This type checking is intended primarily for code which calls the decorated |
| 18 |
function. As Twisted isn't fully type-hinted yet, and in particular Deferred |
| 19 |
does not yet have a generic type argument so that the eventual result type can |
| 20 |
vary, the analysis of the return type of a ``@run_in_reactor`` function/method |
| 21 |
does not account for a Deferred result. This requires you to lie to the type |
| 22 |
checker when returning a Deferred; just cast it to the known, eventual result |
| 23 |
type using ``typing.cast``. For example:: |
| 24 |
|
| 25 |
@run_in_reactor |
| 26 |
def get_time_in_x_seconds(delay: float) -> float: |
| 27 |
def get_time() -> float: |
| 28 |
return reactor.seconds() # type: ignore |
| 29 |
|
| 30 |
if delay < 0.001: |
| 31 |
# Close enough; just return the current time. |
| 32 |
return get_time() |
| 33 |
else: |
| 34 |
d = Deferred() |
| 35 |
|
| 36 |
def complete(): |
| 37 |
d.callback(get_time()) |
| 38 |
|
| 39 |
reactor.callLater(delay, complete) # type: ignore |
| 40 |
return typing.cast(float, d) |
| 41 |
|
| 42 |
If the mypy plugin is correctly installed, the client code will expect a float |
| 43 |
from the ``wait()`` of the ``EventualResult`` returned by a call to this |
| 44 |
function:: |
| 45 |
|
| 46 |
# OK |
| 47 |
t1: float = get_time_in_x_seconds(2).wait(3) |
| 48 |
print(f"The reactor time is {t1}") |
| 49 |
|
| 50 |
# mypy error: Incompatible types in assignment |
| 51 |
# (expression has type "float", variable has type "str") |
| 52 |
t2: str = get_time_in_x_seconds(2).wait(3) |
| 53 |
print(f"The reactor time is {t2}") |
| 54 |
|
| 55 |
.. _PEP 612 — Parameter Specification Variables: https://www.python.org/dev/peps/pep-0612/ |
| 56 |
.. _Configuring mypy to use plugins: https://mypy.readthedocs.io/en/latest/extending_mypy.html#configuring-mypy-to-use-plugins |