Base Class
All switch entities inherit fromSwitchEntity, which extends ToggleEntity. The class is defined in homeassistant.components.switch.
Entity Description
Switch entities can optionally useSwitchEntityDescription to define static metadata:
Required Methods
turn_on
Turn the switch on.turn_off
Turn the switch off.Optional Properties
is_on
Return the current state of the switch.device_class
Indicates the type of switch.OUTLET- Power outletSWITCH- Generic switch
Services
The switch platform automatically registers these services:switch.turn_on- Turn the switch onswitch.turn_off- Turn the switch offswitch.toggle- Toggle the switch state
Example Implementation
Async Implementation
For async devices, override the async methods:Real-World Example
From the demo integration (homeassistant/components/demo/switch.py):
Toggle Support
Switches automatically support toggling via the inheritedToggleEntity base class:
Assumed State
For devices where the state cannot be read:Optimistic Updates
For fast UI response while waiting for device confirmation:Important Notes
- Always call
schedule_update_ha_state()(sync) orasync_write_ha_state()(async) after changing state - Switches inherit from
ToggleEntity, which provides thetogglefunctionality - Set
_attr_should_poll = Falsefor switches that receive push updates - Use
_attr_assumed_state = Truewhen you can’t read back the actual state - The
turn_onandturn_offmethods should update_attr_is_onto reflect the new state