| 1 |
Additional features |
| 2 |
------------------- |
| 3 |
|
| 4 |
This section discusses various features that did not fit in naturally in one |
| 5 |
of the previous sections. |
| 6 |
|
| 7 |
.. _dataclasses_support: |
| 8 |
|
| 9 |
Dataclasses |
| 10 |
*********** |
| 11 |
|
| 12 |
The :py:mod:`dataclasses` module allows defining and customizing simple |
| 13 |
boilerplate-free classes. They can be defined using the |
| 14 |
:py:func:`@dataclasses.dataclass <python:dataclasses.dataclass>` decorator: |
| 15 |
|
| 16 |
.. code-block:: python |
| 17 |
|
| 18 |
from dataclasses import dataclass, field |
| 19 |
|
| 20 |
@dataclass |
| 21 |
class Application: |
| 22 |
name: str |
| 23 |
plugins: list[str] = field(default_factory=list) |
| 24 |
|
| 25 |
test = Application("Testing...") # OK |
| 26 |
bad = Application("Testing...", "with plugin") # Error: list[str] expected |
| 27 |
|
| 28 |
Mypy will detect special methods (such as :py:meth:`__lt__ <object.__lt__>`) depending on the flags used to |
| 29 |
define dataclasses. For example: |
| 30 |
|
| 31 |
.. code-block:: python |
| 32 |
|
| 33 |
from dataclasses import dataclass |
| 34 |
|
| 35 |
@dataclass(order=True) |
| 36 |
class OrderedPoint: |
| 37 |
x: int |
| 38 |
y: int |
| 39 |
|
| 40 |
@dataclass(order=False) |
| 41 |
class UnorderedPoint: |
| 42 |
x: int |
| 43 |
y: int |
| 44 |
|
| 45 |
OrderedPoint(1, 2) < OrderedPoint(3, 4) # OK |
| 46 |
UnorderedPoint(1, 2) < UnorderedPoint(3, 4) # Error: Unsupported operand types |
| 47 |
|
| 48 |
Dataclasses can be generic and can be used in any other way a normal |
| 49 |
class can be used (Python 3.12 syntax): |
| 50 |
|
| 51 |
.. code-block:: python |
| 52 |
|
| 53 |
from dataclasses import dataclass |
| 54 |
|
| 55 |
@dataclass |
| 56 |
class BoxedData[T]: |
| 57 |
data: T |
| 58 |
label: str |
| 59 |
|
| 60 |
def unbox[T](bd: BoxedData[T]) -> T: |
| 61 |
... |
| 62 |
|
| 63 |
val = unbox(BoxedData(42, "<important>")) # OK, inferred type is int |
| 64 |
|
| 65 |
For more information see :doc:`official docs <python:library/dataclasses>` |
| 66 |
and :pep:`557`. |
| 67 |
|
| 68 |
Caveats/Known Issues |
| 69 |
==================== |
| 70 |
|
| 71 |
Some functions in the :py:mod:`dataclasses` module, such as :py:func:`~dataclasses.asdict`, |
| 72 |
have imprecise (too permissive) types. This will be fixed in future releases. |
| 73 |
|
| 74 |
Mypy does not yet recognize aliases of :py:func:`dataclasses.dataclass <dataclasses.dataclass>`, and will |
| 75 |
probably never recognize dynamically computed decorators. The following example |
| 76 |
does **not** work: |
| 77 |
|
| 78 |
.. code-block:: python |
| 79 |
|
| 80 |
from dataclasses import dataclass |
| 81 |
|
| 82 |
dataclass_alias = dataclass |
| 83 |
def dataclass_wrapper(cls): |
| 84 |
return dataclass(cls) |
| 85 |
|
| 86 |
@dataclass_alias |
| 87 |
class AliasDecorated: |
| 88 |
""" |
| 89 |
Mypy doesn't recognize this as a dataclass because it is decorated by an |
| 90 |
alias of `dataclass` rather than by `dataclass` itself. |
| 91 |
""" |
| 92 |
attribute: int |
| 93 |
|
| 94 |
AliasDecorated(attribute=1) # error: Unexpected keyword argument |
| 95 |
|
| 96 |
|
| 97 |
To have Mypy recognize a wrapper of :py:func:`dataclasses.dataclass <dataclasses.dataclass>` |
| 98 |
as a dataclass decorator, consider using the :py:func:`~typing.dataclass_transform` |
| 99 |
decorator (example uses Python 3.12 syntax): |
| 100 |
|
| 101 |
.. code-block:: python |
| 102 |
|
| 103 |
from dataclasses import dataclass, Field |
| 104 |
from typing import dataclass_transform |
| 105 |
|
| 106 |
@dataclass_transform(field_specifiers=(Field,)) |
| 107 |
def my_dataclass[T](cls: type[T]) -> type[T]: |
| 108 |
... |
| 109 |
return dataclass(cls) |
| 110 |
|
| 111 |
|
| 112 |
Data Class Transforms |
| 113 |
********************* |
| 114 |
|
| 115 |
Mypy supports the :py:func:`~typing.dataclass_transform` decorator as described in |
| 116 |
`PEP 681 <https://www.python.org/dev/peps/pep-0681/#the-dataclass-transform-decorator>`_. |
| 117 |
|
| 118 |
.. note:: |
| 119 |
|
| 120 |
Pragmatically, mypy will assume such classes have the internal attribute :code:`__dataclass_fields__` |
| 121 |
(even though they might lack it in runtime) and will assume functions such as :py:func:`dataclasses.is_dataclass` |
| 122 |
and :py:func:`dataclasses.fields` treat them as if they were dataclasses |
| 123 |
(even though they may fail at runtime). |
| 124 |
|
| 125 |
.. _attrs_package: |
| 126 |
|
| 127 |
The attrs package |
| 128 |
***************** |
| 129 |
|
| 130 |
:doc:`attrs <attrs:index>` is a package that lets you define |
| 131 |
classes without writing boilerplate code. Mypy can detect uses of the |
| 132 |
package and will generate the necessary method definitions for decorated |
| 133 |
classes using the type annotations it finds. |
| 134 |
Type annotations can be added as follows: |
| 135 |
|
| 136 |
.. code-block:: python |
| 137 |
|
| 138 |
import attrs |
| 139 |
|
| 140 |
@attrs.define |
| 141 |
class A: |
| 142 |
one: int |
| 143 |
two: int = 7 |
| 144 |
three: int = attrs.field(8) |
| 145 |
|
| 146 |
If you're using ``auto_attribs=False`` you must use ``attrs.field``: |
| 147 |
|
| 148 |
.. code-block:: python |
| 149 |
|
| 150 |
import attrs |
| 151 |
|
| 152 |
@attrs.define |
| 153 |
class A: |
| 154 |
one: int = attrs.field() # Variable annotation (Python 3.6+) |
| 155 |
two = attrs.field() # type: int # Type comment |
| 156 |
three = attrs.field(type=int) # type= argument |
| 157 |
|
| 158 |
Typeshed has a couple of "white lie" annotations to make type checking |
| 159 |
easier. :py:func:`attrs.field` and :py:class:`attrs.Factory` actually return objects, but the |
| 160 |
annotation says these return the types that they expect to be assigned to. |
| 161 |
That enables this to work: |
| 162 |
|
| 163 |
.. code-block:: python |
| 164 |
|
| 165 |
import attrs |
| 166 |
|
| 167 |
@attrs.define |
| 168 |
class A: |
| 169 |
one: int = attrs.field(8) |
| 170 |
two: dict[str, str] = attrs.Factory(dict) |
| 171 |
bad: str = attrs.field(16) # Error: can't assign int to str |
| 172 |
|
| 173 |
Caveats/Known Issues |
| 174 |
==================== |
| 175 |
|
| 176 |
* The detection of attr classes and attributes works by function name only. |
| 177 |
This means that if you have your own helper functions that, for example, |
| 178 |
``return attrs.field()`` mypy will not see them. |
| 179 |
|
| 180 |
* All boolean arguments that mypy cares about must be literal ``True`` or ``False``. |
| 181 |
e.g the following will not work: |
| 182 |
|
| 183 |
.. code-block:: python |
| 184 |
|
| 185 |
import attrs |
| 186 |
YES = True |
| 187 |
@attrs.define(init=YES) |
| 188 |
class A: |
| 189 |
... |
| 190 |
|
| 191 |
* Currently, ``converter`` only supports named functions. If mypy finds something else it |
| 192 |
will complain about not understanding the argument and the type annotation in |
| 193 |
:py:meth:`__init__ <object.__init__>` will be replaced by ``Any``. |
| 194 |
|
| 195 |
* :ref:`Validator decorators <attrs:examples-validators>` |
| 196 |
and `default decorators <https://www.attrs.org/en/stable/examples.html#defaults>`_ |
| 197 |
are not type-checked against the attribute they are setting/validating. |
| 198 |
|
| 199 |
* Method definitions added by mypy currently overwrite any existing method |
| 200 |
definitions. |
| 201 |
|
| 202 |
.. _remote-cache: |
| 203 |
|
| 204 |
Using a remote cache to speed up mypy runs |
| 205 |
****************************************** |
| 206 |
|
| 207 |
Mypy performs type checking *incrementally*, reusing results from |
| 208 |
previous runs to speed up successive runs. If you are type checking a |
| 209 |
large codebase, mypy can still be sometimes slower than desirable. For |
| 210 |
example, if you create a new branch based on a much more recent commit |
| 211 |
than the target of the previous mypy run, mypy may have to |
| 212 |
process almost every file, as a large fraction of source files may |
| 213 |
have changed. This can also happen after you've rebased a local |
| 214 |
branch. |
| 215 |
|
| 216 |
Mypy supports using a *remote cache* to improve performance in cases |
| 217 |
such as the above. In a large codebase, remote caching can sometimes |
| 218 |
speed up mypy runs by a factor of 10, or more. |
| 219 |
|
| 220 |
Mypy doesn't include all components needed to set |
| 221 |
this up -- generally you will have to perform some simple integration |
| 222 |
with your Continuous Integration (CI) or build system to configure |
| 223 |
mypy to use a remote cache. This discussion assumes you have a CI |
| 224 |
system set up for the mypy build you want to speed up, and that you |
| 225 |
are using a central git repository. Generalizing to different |
| 226 |
environments should not be difficult. |
| 227 |
|
| 228 |
Here are the main components needed: |
| 229 |
|
| 230 |
* A shared repository for storing mypy cache files for all landed commits. |
| 231 |
|
| 232 |
* CI build that uploads mypy incremental cache files to the shared repository for |
| 233 |
each commit for which the CI build runs. |
| 234 |
|
| 235 |
* A wrapper script around mypy that developers use to run mypy with remote |
| 236 |
caching enabled. |
| 237 |
|
| 238 |
Below we discuss each of these components in some detail. |
| 239 |
|
| 240 |
Shared repository for cache files |
| 241 |
================================= |
| 242 |
|
| 243 |
You need a repository that allows you to upload mypy cache files from |
| 244 |
your CI build and make the cache files available for download based on |
| 245 |
a commit id. A simple approach would be to produce an archive of the |
| 246 |
``.mypy_cache`` directory (which contains the mypy cache data) as a |
| 247 |
downloadable *build artifact* from your CI build (depending on the |
| 248 |
capabilities of your CI system). Alternatively, you could upload the |
| 249 |
data to a web server or to S3, for example. |
| 250 |
|
| 251 |
Continuous Integration build |
| 252 |
============================ |
| 253 |
|
| 254 |
The CI build would run a regular mypy build and create an archive containing |
| 255 |
the ``.mypy_cache`` directory produced by the build. Finally, it will produce |
| 256 |
the cache as a build artifact or upload it to a repository where it is |
| 257 |
accessible by the mypy wrapper script. |
| 258 |
|
| 259 |
Your CI script might work like this: |
| 260 |
|
| 261 |
* Run mypy normally. This will generate cache data under the |
| 262 |
``.mypy_cache`` directory. |
| 263 |
|
| 264 |
* Create a tarball from the ``.mypy_cache`` directory. |
| 265 |
|
| 266 |
* Determine the current git master branch commit id (say, using |
| 267 |
``git rev-parse HEAD``). |
| 268 |
|
| 269 |
* Upload the tarball to the shared repository with a name derived from the |
| 270 |
commit id. |
| 271 |
|
| 272 |
Mypy wrapper script |
| 273 |
=================== |
| 274 |
|
| 275 |
The wrapper script is used by developers to run mypy locally during |
| 276 |
development instead of invoking mypy directly. The wrapper first |
| 277 |
populates the local ``.mypy_cache`` directory from the shared |
| 278 |
repository and then runs a normal incremental build. |
| 279 |
|
| 280 |
The wrapper script needs some logic to determine the most recent |
| 281 |
central repository commit (by convention, the ``origin/master`` branch |
| 282 |
for git) the local development branch is based on. In a typical git |
| 283 |
setup you can do it like this: |
| 284 |
|
| 285 |
.. code:: |
| 286 |
|
| 287 |
git merge-base HEAD origin/master |
| 288 |
|
| 289 |
The next step is to download the cache data (contents of the |
| 290 |
``.mypy_cache`` directory) from the shared repository based on the |
| 291 |
commit id of the merge base produced by the git command above. The |
| 292 |
script will decompress the data so that mypy will start with a fresh |
| 293 |
``.mypy_cache``. Finally, the script runs mypy normally. And that's all! |
| 294 |
|
| 295 |
Caching with mypy daemon |
| 296 |
======================== |
| 297 |
|
| 298 |
You can also use remote caching with the :ref:`mypy daemon <mypy_daemon>`. |
| 299 |
The remote cache will significantly speed up the first ``dmypy check`` |
| 300 |
run after starting or restarting the daemon. |
| 301 |
|
| 302 |
The mypy daemon requires extra fine-grained dependency data in |
| 303 |
the cache files which aren't included by default. To use caching with |
| 304 |
the mypy daemon, use the :option:`--cache-fine-grained <mypy --cache-fine-grained>` option in your CI |
| 305 |
build:: |
| 306 |
|
| 307 |
$ mypy --cache-fine-grained <args...> |
| 308 |
|
| 309 |
This flag adds extra information for the daemon to the cache. In |
| 310 |
order to use this extra information, you will also need to use the |
| 311 |
``--use-fine-grained-cache`` option with ``dmypy start`` or |
| 312 |
``dmypy restart``. Example:: |
| 313 |
|
| 314 |
$ dmypy start -- --use-fine-grained-cache <options...> |
| 315 |
|
| 316 |
Now your first ``dmypy check`` run should be much faster, as it can use |
| 317 |
cache information to avoid processing the whole program. |
| 318 |
|
| 319 |
Refinements |
| 320 |
=========== |
| 321 |
|
| 322 |
There are several optional refinements that may improve things further, |
| 323 |
at least if your codebase is hundreds of thousands of lines or more: |
| 324 |
|
| 325 |
* If the wrapper script determines that the merge base hasn't changed |
| 326 |
from a previous run, there's no need to download the cache data and |
| 327 |
it's better to instead reuse the existing local cache data. |
| 328 |
|
| 329 |
* If you use the mypy daemon, you may want to restart the daemon each time |
| 330 |
after the merge base or local branch has changed to avoid processing a |
| 331 |
potentially large number of changes in an incremental build, as this can |
| 332 |
be much slower than downloading cache data and restarting the daemon. |
| 333 |
|
| 334 |
* If the current local branch is based on a very recent master commit, |
| 335 |
the remote cache data may not yet be available for that commit, as |
| 336 |
there will necessarily be some latency to build the cache files. It |
| 337 |
may be a good idea to look for cache data for, say, the 5 latest |
| 338 |
master commits and use the most recent data that is available. |
| 339 |
|
| 340 |
* If the remote cache is not accessible for some reason (say, from a public |
| 341 |
network), the script can still fall back to a normal incremental build. |
| 342 |
|
| 343 |
* You can have multiple local cache directories for different local branches |
| 344 |
using the :option:`--cache-dir <mypy --cache-dir>` option. If the user switches to an existing |
| 345 |
branch where downloaded cache data is already available, you can continue |
| 346 |
to use the existing cache data instead of redownloading the data. |
| 347 |
|
| 348 |
* You can set up your CI build to use a remote cache to speed up the |
| 349 |
CI build. This would be particularly useful if each CI build starts |
| 350 |
from a fresh state without access to cache files from previous |
| 351 |
builds. It's still recommended to run a full, non-incremental |
| 352 |
mypy build to create the cache data, as repeatedly updating cache |
| 353 |
data incrementally could result in drift over a long time period (due |
| 354 |
to a mypy caching issue, perhaps). |
| 355 |
|
| 356 |
.. _extended_callable: |
| 357 |
|
| 358 |
Extended Callable types |
| 359 |
*********************** |
| 360 |
|
| 361 |
.. note:: |
| 362 |
|
| 363 |
This feature is deprecated. You can use |
| 364 |
:ref:`callback protocols <callback_protocols>` as a replacement. |
| 365 |
|
| 366 |
As an experimental mypy extension, you can specify :py:class:`~collections.abc.Callable` types |
| 367 |
that support keyword arguments, optional arguments, and more. When |
| 368 |
you specify the arguments of a :py:class:`~collections.abc.Callable`, you can choose to supply just |
| 369 |
the type of a nameless positional argument, or an "argument specifier" |
| 370 |
representing a more complicated form of argument. This allows one to |
| 371 |
more closely emulate the full range of possibilities given by the |
| 372 |
``def`` statement in Python. |
| 373 |
|
| 374 |
As an example, here's a complicated function definition and the |
| 375 |
corresponding :py:class:`~collections.abc.Callable`: |
| 376 |
|
| 377 |
.. code-block:: python |
| 378 |
|
| 379 |
from collections.abc import Callable |
| 380 |
from mypy_extensions import (Arg, DefaultArg, NamedArg, |
| 381 |
DefaultNamedArg, VarArg, KwArg) |
| 382 |
|
| 383 |
def func(__a: int, # This convention is for nameless arguments |
| 384 |
b: int, |
| 385 |
c: int = 0, |
| 386 |
*args: int, |
| 387 |
d: int, |
| 388 |
e: int = 0, |
| 389 |
**kwargs: int) -> int: |
| 390 |
... |
| 391 |
|
| 392 |
F = Callable[[int, # Or Arg(int) |
| 393 |
Arg(int, 'b'), |
| 394 |
DefaultArg(int, 'c'), |
| 395 |
VarArg(int), |
| 396 |
NamedArg(int, 'd'), |
| 397 |
DefaultNamedArg(int, 'e'), |
| 398 |
KwArg(int)], |
| 399 |
int] |
| 400 |
|
| 401 |
f: F = func |
| 402 |
|
| 403 |
Argument specifiers are special function calls that can specify the |
| 404 |
following aspects of an argument: |
| 405 |
|
| 406 |
- its type (the only thing that the basic format supports) |
| 407 |
|
| 408 |
- its name (if it has one) |
| 409 |
|
| 410 |
- whether it may be omitted |
| 411 |
|
| 412 |
- whether it may or must be passed using a keyword |
| 413 |
|
| 414 |
- whether it is a ``*args`` argument (representing the remaining |
| 415 |
positional arguments) |
| 416 |
|
| 417 |
- whether it is a ``**kwargs`` argument (representing the remaining |
| 418 |
keyword arguments) |
| 419 |
|
| 420 |
The following functions are available in ``mypy_extensions`` for this |
| 421 |
purpose: |
| 422 |
|
| 423 |
.. code-block:: python |
| 424 |
|
| 425 |
def Arg(type=Any, name=None): |
| 426 |
# A normal, mandatory, positional argument. |
| 427 |
# If the name is specified it may be passed as a keyword. |
| 428 |
|
| 429 |
def DefaultArg(type=Any, name=None): |
| 430 |
# An optional positional argument (i.e. with a default value). |
| 431 |
# If the name is specified it may be passed as a keyword. |
| 432 |
|
| 433 |
def NamedArg(type=Any, name=None): |
| 434 |
# A mandatory keyword-only argument. |
| 435 |
|
| 436 |
def DefaultNamedArg(type=Any, name=None): |
| 437 |
# An optional keyword-only argument (i.e. with a default value). |
| 438 |
|
| 439 |
def VarArg(type=Any): |
| 440 |
# A *args-style variadic positional argument. |
| 441 |
# A single VarArg() specifier represents all remaining |
| 442 |
# positional arguments. |
| 443 |
|
| 444 |
def KwArg(type=Any): |
| 445 |
# A **kwargs-style variadic keyword argument. |
| 446 |
# A single KwArg() specifier represents all remaining |
| 447 |
# keyword arguments. |
| 448 |
|
| 449 |
In all cases, the ``type`` argument defaults to ``Any``, and if the |
| 450 |
``name`` argument is omitted the argument has no name (the name is |
| 451 |
required for ``NamedArg`` and ``DefaultNamedArg``). A basic |
| 452 |
:py:class:`~collections.abc.Callable` such as |
| 453 |
|
| 454 |
.. code-block:: python |
| 455 |
|
| 456 |
MyFunc = Callable[[int, str, int], float] |
| 457 |
|
| 458 |
is equivalent to the following: |
| 459 |
|
| 460 |
.. code-block:: python |
| 461 |
|
| 462 |
MyFunc = Callable[[Arg(int), Arg(str), Arg(int)], float] |
| 463 |
|
| 464 |
A :py:class:`~collections.abc.Callable` with unspecified argument types, such as |
| 465 |
|
| 466 |
.. code-block:: python |
| 467 |
|
| 468 |
MyOtherFunc = Callable[..., int] |
| 469 |
|
| 470 |
is (roughly) equivalent to |
| 471 |
|
| 472 |
.. code-block:: python |
| 473 |
|
| 474 |
MyOtherFunc = Callable[[VarArg(), KwArg()], int] |
| 475 |
|
| 476 |
.. note:: |
| 477 |
|
| 478 |
Each of the functions above currently just returns its ``type`` |
| 479 |
argument at runtime, so the information contained in the argument |
| 480 |
specifiers is not available at runtime. This limitation is |
| 481 |
necessary for backwards compatibility with the existing |
| 482 |
``typing.py`` module as present in the Python 3.5+ standard library |
| 483 |
and distributed via PyPI. |