| 1 |
.. _extending-mypy: |
| 2 |
|
| 3 |
Extending and integrating mypy |
| 4 |
============================== |
| 5 |
|
| 6 |
.. _integrating-mypy: |
| 7 |
|
| 8 |
Integrating mypy into another Python application |
| 9 |
************************************************ |
| 10 |
|
| 11 |
It is possible to integrate mypy into another Python 3 application by |
| 12 |
importing ``mypy.api`` and calling the ``run`` function with a parameter of type ``list[str]``, containing |
| 13 |
what normally would have been the command line arguments to mypy. |
| 14 |
|
| 15 |
Function ``run`` returns a ``tuple[str, str, int]``, namely |
| 16 |
``(<normal_report>, <error_report>, <exit_status>)``, in which ``<normal_report>`` |
| 17 |
is what mypy normally writes to :py:data:`sys.stdout`, ``<error_report>`` is what mypy |
| 18 |
normally writes to :py:data:`sys.stderr` and ``exit_status`` is the exit status mypy normally |
| 19 |
returns to the operating system. |
| 20 |
|
| 21 |
A trivial example of using the api is the following |
| 22 |
|
| 23 |
.. code-block:: python |
| 24 |
|
| 25 |
import sys |
| 26 |
from mypy import api |
| 27 |
|
| 28 |
result = api.run(sys.argv[1:]) |
| 29 |
|
| 30 |
if result[0]: |
| 31 |
print('\nType checking report:\n') |
| 32 |
print(result[0]) # stdout |
| 33 |
|
| 34 |
if result[1]: |
| 35 |
print('\nError report:\n') |
| 36 |
print(result[1]) # stderr |
| 37 |
|
| 38 |
print('\nExit status:', result[2]) |
| 39 |
|
| 40 |
|
| 41 |
.. _extending-mypy-using-plugins: |
| 42 |
|
| 43 |
Extending mypy using plugins |
| 44 |
**************************** |
| 45 |
|
| 46 |
Python is a highly dynamic language and has extensive metaprogramming |
| 47 |
capabilities. Many popular libraries use these to create APIs that may |
| 48 |
be more flexible and/or natural for humans, but are hard to express using |
| 49 |
static types. Extending the :pep:`484` type system to accommodate all existing |
| 50 |
dynamic patterns is impractical and often just impossible. |
| 51 |
|
| 52 |
Mypy supports a plugin system that lets you customize the way mypy type checks |
| 53 |
code. This can be useful if you want to extend mypy so it can type check code |
| 54 |
that uses a library that is difficult to express using just :pep:`484` types. |
| 55 |
|
| 56 |
The plugin system is focused on improving mypy's understanding |
| 57 |
of *semantics* of third party frameworks. There is currently no way to define |
| 58 |
new first class kinds of types. |
| 59 |
|
| 60 |
.. note:: |
| 61 |
|
| 62 |
The plugin system is experimental and prone to change. If you want to write |
| 63 |
a mypy plugin, we recommend you start by contacting the mypy core developers |
| 64 |
on `gitter <https://gitter.im/python/typing>`_. In particular, there are |
| 65 |
no guarantees about backwards compatibility. |
| 66 |
|
| 67 |
Backwards incompatible changes may be made without a deprecation period, |
| 68 |
but we will announce them in |
| 69 |
`the plugin API changes announcement issue <https://github.com/python/mypy/issues/6617>`_. |
| 70 |
|
| 71 |
Configuring mypy to use plugins |
| 72 |
******************************* |
| 73 |
|
| 74 |
Plugins are Python files that can be specified in a mypy |
| 75 |
:ref:`config file <config-file>` using the :confval:`plugins` option and one of the two formats: relative or |
| 76 |
absolute path to the plugin file, or a module name (if the plugin |
| 77 |
is installed using ``pip install`` in the same virtual environment where mypy |
| 78 |
is running). The two formats can be mixed, for example: |
| 79 |
|
| 80 |
.. code-block:: ini |
| 81 |
|
| 82 |
[mypy] |
| 83 |
plugins = /one/plugin.py, other.plugin |
| 84 |
|
| 85 |
Mypy will try to import the plugins and will look for an entry point function |
| 86 |
named ``plugin``. If the plugin entry point function has a different name, it |
| 87 |
can be specified after colon: |
| 88 |
|
| 89 |
.. code-block:: ini |
| 90 |
|
| 91 |
[mypy] |
| 92 |
plugins = custom_plugin:custom_entry_point |
| 93 |
|
| 94 |
In the following sections we describe the basics of the plugin system with |
| 95 |
some examples. For more technical details, please read the docstrings in |
| 96 |
`mypy/plugin.py <https://github.com/python/mypy/blob/master/mypy/plugin.py>`_ |
| 97 |
in mypy source code. Also you can find good examples in the bundled plugins |
| 98 |
located in `mypy/plugins <https://github.com/python/mypy/tree/master/mypy/plugins>`_. |
| 99 |
|
| 100 |
High-level overview |
| 101 |
******************* |
| 102 |
|
| 103 |
Every entry point function should accept a single string argument |
| 104 |
that is a full mypy version and return a subclass of ``mypy.plugin.Plugin``: |
| 105 |
|
| 106 |
.. code-block:: python |
| 107 |
|
| 108 |
from mypy.plugin import Plugin |
| 109 |
|
| 110 |
class CustomPlugin(Plugin): |
| 111 |
def get_type_analyze_hook(self, fullname: str): |
| 112 |
# see explanation below |
| 113 |
... |
| 114 |
|
| 115 |
def plugin(version: str): |
| 116 |
# ignore version argument if the plugin works with all mypy versions. |
| 117 |
return CustomPlugin |
| 118 |
|
| 119 |
During different phases of analyzing the code (first in semantic analysis, |
| 120 |
and then in type checking) mypy calls plugin methods such as |
| 121 |
``get_type_analyze_hook()`` on user plugins. This particular method, for example, |
| 122 |
can return a callback that mypy will use to analyze unbound types with the given |
| 123 |
full name. See the full plugin hook method list :ref:`below <plugin_hooks>`. |
| 124 |
|
| 125 |
Mypy maintains a list of plugins it gets from the config file plus the default |
| 126 |
(built-in) plugin that is always enabled. Mypy calls a method once for each |
| 127 |
plugin in the list until one of the methods returns a non-``None`` value. |
| 128 |
This callback will be then used to customize the corresponding aspect of |
| 129 |
analyzing/checking the current abstract syntax tree node. |
| 130 |
|
| 131 |
The callback returned by the ``get_xxx`` method will be given a detailed |
| 132 |
current context and an API to create new nodes, new types, emit error messages, |
| 133 |
etc., and the result will be used for further processing. |
| 134 |
|
| 135 |
Plugin developers should ensure that their plugins work well in incremental and |
| 136 |
daemon modes. In particular, plugins should not hold global state due to caching |
| 137 |
of plugin hook results. |
| 138 |
|
| 139 |
.. _plugin_hooks: |
| 140 |
|
| 141 |
Current list of plugin hooks |
| 142 |
**************************** |
| 143 |
|
| 144 |
**get_type_analyze_hook()** customizes behaviour of the type analyzer. |
| 145 |
For example, :pep:`484` doesn't support defining variadic generic types: |
| 146 |
|
| 147 |
.. code-block:: python |
| 148 |
|
| 149 |
from lib import Vector |
| 150 |
|
| 151 |
a: Vector[int, int] |
| 152 |
b: Vector[int, int, int] |
| 153 |
|
| 154 |
When analyzing this code, mypy will call ``get_type_analyze_hook("lib.Vector")``, |
| 155 |
so the plugin can return some valid type for each variable. |
| 156 |
|
| 157 |
**get_function_hook()** is used to adjust the return type of a function call. |
| 158 |
This hook will be also called for instantiation of classes. |
| 159 |
This is a good choice if the return type is too complex |
| 160 |
to be expressed by regular python typing. |
| 161 |
|
| 162 |
**get_function_signature_hook()** is used to adjust the signature of a function. |
| 163 |
|
| 164 |
**get_method_hook()** is the same as ``get_function_hook()`` but for methods |
| 165 |
instead of module level functions. |
| 166 |
|
| 167 |
**get_method_signature_hook()** is used to adjust the signature of a method. |
| 168 |
This includes special Python methods except :py:meth:`~object.__init__` and :py:meth:`~object.__new__`. |
| 169 |
For example in this code: |
| 170 |
|
| 171 |
.. code-block:: python |
| 172 |
|
| 173 |
from ctypes import Array, c_int |
| 174 |
|
| 175 |
x: Array[c_int] |
| 176 |
x[0] = 42 |
| 177 |
|
| 178 |
mypy will call ``get_method_signature_hook("ctypes.Array.__setitem__")`` |
| 179 |
so that the plugin can mimic the :py:mod:`ctypes` auto-convert behavior. |
| 180 |
|
| 181 |
**get_attribute_hook()** overrides instance member field lookups and property |
| 182 |
access (not method calls). This hook is only called for |
| 183 |
fields which already exist on the class. *Exception:* if :py:meth:`__getattr__ <object.__getattr__>` or |
| 184 |
:py:meth:`__getattribute__ <object.__getattribute__>` is a method on the class, the hook is called for all |
| 185 |
fields which do not refer to methods. |
| 186 |
|
| 187 |
**get_class_attribute_hook()** is similar to above, but for attributes on classes rather than instances. |
| 188 |
Unlike above, this does not have special casing for :py:meth:`__getattr__ <object.__getattr__>` or |
| 189 |
:py:meth:`__getattribute__ <object.__getattribute__>`. |
| 190 |
|
| 191 |
**get_class_decorator_hook()** can be used to update class definition for |
| 192 |
given class decorators. For example, you can add some attributes to the class |
| 193 |
to match runtime behaviour: |
| 194 |
|
| 195 |
.. code-block:: python |
| 196 |
|
| 197 |
from dataclasses import dataclass |
| 198 |
|
| 199 |
@dataclass # built-in plugin adds `__init__` method here |
| 200 |
class User: |
| 201 |
name: str |
| 202 |
|
| 203 |
user = User(name='example') # mypy can understand this using a plugin |
| 204 |
|
| 205 |
**get_metaclass_hook()** is similar to above, but for metaclasses. |
| 206 |
|
| 207 |
**get_base_class_hook()** is similar to above, but for base classes. |
| 208 |
|
| 209 |
**get_dynamic_class_hook()** can be used to allow dynamic class definitions |
| 210 |
in mypy. This plugin hook is called for every assignment to a simple name |
| 211 |
where right hand side is a function call: |
| 212 |
|
| 213 |
.. code-block:: python |
| 214 |
|
| 215 |
from lib import dynamic_class |
| 216 |
|
| 217 |
X = dynamic_class('X', []) |
| 218 |
|
| 219 |
For such definition, mypy will call ``get_dynamic_class_hook("lib.dynamic_class")``. |
| 220 |
The plugin should create the corresponding ``mypy.nodes.TypeInfo`` object, and |
| 221 |
place it into a relevant symbol table. (Instances of this class represent |
| 222 |
classes in mypy and hold essential information such as qualified name, |
| 223 |
method resolution order, etc.) |
| 224 |
|
| 225 |
**get_customize_class_mro_hook()** can be used to modify class MRO (for example |
| 226 |
insert some entries there) before the class body is analyzed. |
| 227 |
|
| 228 |
**get_additional_deps()** can be used to add new dependencies for a |
| 229 |
module. It is called before semantic analysis. For example, this can |
| 230 |
be used if a library has dependencies that are dynamically loaded |
| 231 |
based on configuration information. |
| 232 |
|
| 233 |
**report_config_data()** can be used if the plugin has some sort of |
| 234 |
per-module configuration that can affect typechecking. In that case, |
| 235 |
when the configuration for a module changes, we want to invalidate |
| 236 |
mypy's cache for that module so that it can be rechecked. This hook |
| 237 |
should be used to report to mypy any relevant configuration data, |
| 238 |
so that mypy knows to recheck the module if the configuration changes. |
| 239 |
The hooks should return data encodable as JSON. |
| 240 |
|
| 241 |
Useful tools |
| 242 |
************ |
| 243 |
|
| 244 |
Mypy ships ``mypy.plugins.proper_plugin`` plugin which can be useful |
| 245 |
for plugin authors, since it finds missing ``get_proper_type()`` calls, |
| 246 |
which is a pretty common mistake. |
| 247 |
|
| 248 |
It is recommended to enable it as a part of your plugin's CI. |