forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Typing
Michael edited this page May 23, 2021
·
2 revisions
- 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] = {...}
- Bad:
- 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
- Bad:
- module splitting
-
common.py
- integration wide used functions and classes
-
const.py
- integration wide used constants (type all as
Final
)
- integration wide used constants (type all as
-
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
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.
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 as PARENT_PLATFORM_SCHEMA
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.