MyPy and Blender

MyPy is a fantastic tool to do static checks of Python code. To make it work well with Blender, there are some tweaks to make to its configuration.

This is the config that I use. You can place it in a pyproject.toml file, or in mypy.ini, whatever you wish.

python_version = 3.7
ignore_missing_imports = True
strict_optional = True
disallow_subclassing_any = False
disallow_any_generics = True
disallow_untyped_calls = True
disallow_incomplete_defs = True
check_untyped_defs = True
disallow_untyped_decorators = True
no_implicit_optional = True
warn_redundant_casts = True
warn_unused_ignores = true
warn_return_any = True

This enforces that a typed function (so one that declares at least one parameter or its return type) only calls into other typed functions. I’ve made mistakes in the past where MyPy ignored an untyped function; the lack of errors made me think incorrectly that the code was ok.

The only thing that MyPy doesn’t like is the way Blender declares properties, for example in operators and property groups. To work around this, use a # type: ignore marker, like this:

from bpy.props import BoolProperty, PropertyGroup
class MyAddonSettings(PropertyGroup):
    enable_feature : BoolProperty(      # type: ignore
        name = "Enable The Feature",
        description = "Turn on this amazing thing and be amazed",

With all of this in place, you can run mypy (for single-file addons) or mypy my_addon (where my_addon is the directory containing the Python sources).

dr. Sybren A. Stüvel
dr. Sybren A. Stüvel
Open Source software developer, photographer, drummer, and electronics tinkerer