Skip to content
Michael edited this page May 23, 2021 · 2 revisions

Hints

  • type empty variable init
    • my_list: list[str] = []
    • my_dict: dict[str, str] = {}
  • annotated types as precise as possible
    • Bad: my_dict: dict = {...}
    • Good: my_dict: dict[str, str] = {...}
  • avoid Any as much as possible
    • Bad: my_dict: dict[str, Any] = {...}
    • Good: my_dict: dict[str, str] = {...}
    • Bad: my_var: Any | None = None
    • Good: my_var: str | None = None
  • module splitting
    • common.py
      • integration wide used functions and classes
    • const.py
      • integration wide used constants (type all as Final)
    • model.py
      • integration wide used type defintions (TypedDicts,...)
  • should not import any platform specific code to the common.py module
  • platform modules (sensor.py, binary_sensor.py, ...) should never import from other platforms

Troubleshooting

You can insert reveal_type(variable) calls inside the code and mypy will print current type, no extra imports required. Don't forget to clean it up because this function only exists when running mypy.

Snippets

Imports

from __future__ import annotations
from typing import Final
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.service import ServiceCall
from homeassistant.config_entries import ConfigEntry

PLATFORM_SCHEMA

PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA

Why do typing?

Typing is helpful to make sure you're using these types correctly. It's helping in a way tests help to protect the code from errors. They're also very helpful for people reading the code which is usually not someone who wrote it.

Clone this wiki locally