Use identity checks for CoreState (#107846)

Some of the checks used ==, and some used is. Switch
everything to is as its faster
This commit is contained in:
J. Nick Koston 2024-01-11 23:21:26 -10:00 committed by GitHub
parent b12291633c
commit 4b7a313ece
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
31 changed files with 45 additions and 45 deletions

View file

@ -721,7 +721,7 @@ class AutomationEntity(BaseAutomationEntity, RestoreEntity):
self._is_enabled = True self._is_enabled = True
# HomeAssistant is starting up # HomeAssistant is starting up
if self.hass.state != CoreState.not_running: if self.hass.state is not CoreState.not_running:
self._async_detach_triggers = await self._async_attach_triggers(False) self._async_detach_triggers = await self._async_attach_triggers(False)
self.async_write_ha_state() self.async_write_ha_state()
return return

View file

@ -412,7 +412,7 @@ class CloudGoogleConfig(AbstractConfig):
if ( if (
not self.enabled not self.enabled
or not self._cloud.is_logged_in or not self._cloud.is_logged_in
or self.hass.state != CoreState.running or self.hass.state is not CoreState.running
): ):
return return
@ -435,7 +435,7 @@ class CloudGoogleConfig(AbstractConfig):
if ( if (
not self.enabled not self.enabled
or not self._cloud.is_logged_in or not self._cloud.is_logged_in
or self.hass.state != CoreState.running or self.hass.state is not CoreState.running
): ):
return return

View file

@ -614,7 +614,7 @@ async def async_setup_entry(
transport = None transport = None
protocol = None protocol = None
while hass.state == CoreState.not_running or hass.is_running: while hass.state is CoreState.not_running or hass.is_running:
# Start DSMR asyncio.Protocol reader # Start DSMR asyncio.Protocol reader
# Reflect connected state in devices state by setting an # Reflect connected state in devices state by setting an
@ -641,7 +641,7 @@ async def async_setup_entry(
await protocol.wait_closed() await protocol.wait_closed()
# Unexpected disconnect # Unexpected disconnect
if hass.state == CoreState.not_running or hass.is_running: if hass.state is CoreState.not_running or hass.is_running:
stop_listener() stop_listener()
transport = None transport = None
@ -673,7 +673,7 @@ async def async_setup_entry(
update_entities_telegram(None) update_entities_telegram(None)
if stop_listener and ( if stop_listener and (
hass.state == CoreState.not_running or hass.is_running hass.state is CoreState.not_running or hass.is_running
): ):
stop_listener() stop_listener()

View file

@ -155,7 +155,7 @@ class EmulatedRoku:
) )
# start immediately if already running # start immediately if already running
if self.hass.state == CoreState.running: if self.hass.state is CoreState.running:
await emulated_roku_start(None) await emulated_roku_start(None)
else: else:
self._unsub_start_listener = self.hass.bus.async_listen_once( self._unsub_start_listener = self.hass.bus.async_listen_once(

View file

@ -270,7 +270,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
): ):
self.hass.create_task(self._check_switch_initial_state()) self.hass.create_task(self._check_switch_initial_state())
if self.hass.state == CoreState.running: if self.hass.state is CoreState.running:
_async_startup() _async_startup()
else: else:
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_startup) self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _async_startup)

View file

@ -93,7 +93,7 @@ class GoogleTravelTimeSensor(SensorEntity):
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Handle when entity is added.""" """Handle when entity is added."""
if self.hass.state != CoreState.running: if self.hass.state is not CoreState.running:
self.hass.bus.async_listen_once( self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, self.first_update EVENT_HOMEASSISTANT_STARTED, self.first_update
) )

View file

@ -353,7 +353,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
) )
hass.data[DOMAIN][entry.entry_id] = entry_data hass.data[DOMAIN][entry.entry_id] = entry_data
if hass.state == CoreState.running: if hass.state is CoreState.running:
await homekit.async_start() await homekit.async_start()
else: else:
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, homekit.async_start) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, homekit.async_start)

View file

@ -261,7 +261,7 @@ class HKDevice:
# Ideally we would know which entities we are about to add # Ideally we would know which entities we are about to add
# so we only poll those chars but that is not possible # so we only poll those chars but that is not possible
# yet. # yet.
attempts = None if self.hass.state == CoreState.running else 1 attempts = None if self.hass.state is CoreState.running else 1
if ( if (
transport == Transport.BLE transport == Transport.BLE
and pairing.accessories and pairing.accessories

View file

@ -404,7 +404,7 @@ class KodiEntity(MediaPlayerEntity):
# If Home Assistant is already in a running state, start the watchdog # If Home Assistant is already in a running state, start the watchdog
# immediately, else trigger it after Home Assistant has finished starting. # immediately, else trigger it after Home Assistant has finished starting.
if self.hass.state == CoreState.running: if self.hass.state is CoreState.running:
await start_watchdog() await start_watchdog()
else: else:
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, start_watchdog) self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, start_watchdog)

View file

@ -413,7 +413,7 @@ class MQTT:
) )
self._pending_unsubscribes: set[str] = set() # topic self._pending_unsubscribes: set[str] = set() # topic
if self.hass.state == CoreState.running: if self.hass.state is CoreState.running:
self._ha_started.set() self._ha_started.set()
else: else:

View file

@ -179,7 +179,7 @@ class NmapDeviceScanner:
seconds=cv.positive_float(config[CONF_CONSIDER_HOME]) seconds=cv.positive_float(config[CONF_CONSIDER_HOME])
) )
self._scan_lock = asyncio.Lock() self._scan_lock = asyncio.Lock()
if self._hass.state == CoreState.running: if self._hass.state is CoreState.running:
await self._async_start_scanner() await self._async_start_scanner()
return return

View file

@ -36,7 +36,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Only poll if hass is running, we need to poll, # Only poll if hass is running, we need to poll,
# and we actually have a way to connect to the device # and we actually have a way to connect to the device
return ( return (
hass.state == CoreState.running hass.state is CoreState.running
and data.poll_needed(service_info, last_poll) and data.poll_needed(service_info, last_poll)
and bool( and bool(
async_ble_device_from_address( async_ble_device_from_address(

View file

@ -254,7 +254,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
async_dispatcher_send(hass, SIGNAL_AVAILABILITY, False) async_dispatcher_send(hass, SIGNAL_AVAILABILITY, False)
# If HA is not stopping, initiate new connection # If HA is not stopping, initiate new connection
if hass.state != CoreState.stopping: if hass.state is not CoreState.stopping:
_LOGGER.warning("Disconnected from Rflink, reconnecting") _LOGGER.warning("Disconnected from Rflink, reconnecting")
hass.async_create_task(connect()) hass.async_create_task(connect())

View file

@ -456,7 +456,7 @@ class SimpliSafe:
@callback @callback
def _async_process_new_notifications(self, system: SystemType) -> None: def _async_process_new_notifications(self, system: SystemType) -> None:
"""Act on any new system notifications.""" """Act on any new system notifications."""
if self._hass.state != CoreState.running: if self._hass.state is not CoreState.running:
# If HASS isn't fully running yet, it may cause the SIMPLISAFE_NOTIFICATION # If HASS isn't fully running yet, it may cause the SIMPLISAFE_NOTIFICATION
# event to fire before dependent components (like automation) are fully # event to fire before dependent components (like automation) are fully
# ready. If that's the case, skip: # ready. If that's the case, skip:

View file

@ -31,7 +31,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
"""Request a refresh.""" """Request a refresh."""
await coordinator.async_request_refresh() await coordinator.async_request_refresh()
if hass.state == CoreState.running: if hass.state is CoreState.running:
await coordinator.async_config_entry_first_refresh() await coordinator.async_config_entry_first_refresh()
else: else:
# Running a speed test during startup can prevent # Running a speed test during startup can prevent

View file

@ -65,7 +65,7 @@ class SwitchbotDataUpdateCoordinator(ActiveBluetoothDataUpdateCoordinator[None])
# Only poll if hass is running, we need to poll, # Only poll if hass is running, we need to poll,
# and we actually have a way to connect to the device # and we actually have a way to connect to the device
return ( return (
self.hass.state == CoreState.running self.hass.state is CoreState.running
and self.device.poll_needed(seconds_since_last_poll) and self.device.poll_needed(seconds_since_last_poll)
and bool( and bool(
bluetooth.async_ble_device_from_address( bluetooth.async_ble_device_from_address(

View file

@ -42,7 +42,7 @@ class TriggerUpdateCoordinator(DataUpdateCoordinator):
async def async_setup(self, hass_config: ConfigType) -> None: async def async_setup(self, hass_config: ConfigType) -> None:
"""Set up the trigger and create entities.""" """Set up the trigger and create entities."""
if self.hass.state == CoreState.running: if self.hass.state is CoreState.running:
await self._attach_triggers() await self._attach_triggers()
else: else:
self._unsub_start = self.hass.bus.async_listen_once( self._unsub_start = self.hass.bus.async_listen_once(

View file

@ -118,7 +118,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# If Home Assistant is already in a running state, register the webhook # If Home Assistant is already in a running state, register the webhook
# immediately, else trigger it after Home Assistant has finished starting. # immediately, else trigger it after Home Assistant has finished starting.
if hass.state == CoreState.running: if hass.state is CoreState.running:
await coordinator.register_webhook() await coordinator.register_webhook()
else: else:
hass.bus.async_listen_once( hass.bus.async_listen_once(

View file

@ -110,7 +110,7 @@ class WazeTravelTime(SensorEntity):
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Handle when entity is added.""" """Handle when entity is added."""
if self.hass.state != CoreState.running: if self.hass.state is not CoreState.running:
self.hass.bus.async_listen_once( self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, self.first_update EVENT_HOMEASSISTANT_STARTED, self.first_update
) )

View file

@ -119,7 +119,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Only poll if hass is running, we need to poll, # Only poll if hass is running, we need to poll,
# and we actually have a way to connect to the device # and we actually have a way to connect to the device
return ( return (
hass.state == CoreState.running hass.state is CoreState.running
and data.poll_needed(service_info, last_poll) and data.poll_needed(service_info, last_poll)
and bool( and bool(
async_ble_device_from_address( async_ble_device_from_address(

View file

@ -191,7 +191,7 @@ class ZWaveNodeFirmwareUpdate(UpdateEntity):
# If hass hasn't started yet, push the next update to the next day so that we # If hass hasn't started yet, push the next update to the next day so that we
# can preserve the offsets we've created between each node # can preserve the offsets we've created between each node
if self.hass.state != CoreState.running: if self.hass.state is not CoreState.running:
self._poll_unsub = async_call_later( self._poll_unsub = async_call_later(
self.hass, timedelta(days=1), self._async_update self.hass, timedelta(days=1), self._async_update
) )

View file

@ -455,7 +455,7 @@ class ConfigEntry:
wait_time, wait_time,
) )
if hass.state == CoreState.running: if hass.state is CoreState.running:
self._async_cancel_retry_setup = async_call_later( self._async_cancel_retry_setup = async_call_later(
hass, wait_time, self._async_get_setup_again_job(hass) hass, wait_time, self._async_get_setup_again_job(hass)
) )

View file

@ -425,7 +425,7 @@ class HomeAssistant:
This method is a coroutine. This method is a coroutine.
""" """
if self.state != CoreState.not_running: if self.state is not CoreState.not_running:
raise RuntimeError("Home Assistant is already running") raise RuntimeError("Home Assistant is already running")
# _async_stop will set this instead of stopping the loop # _async_stop will set this instead of stopping the loop
@ -474,7 +474,7 @@ class HomeAssistant:
# Allow automations to set up the start triggers before changing state # Allow automations to set up the start triggers before changing state
await asyncio.sleep(0) await asyncio.sleep(0)
if self.state != CoreState.starting: if self.state is not CoreState.starting:
_LOGGER.warning( _LOGGER.warning(
"Home Assistant startup has been interrupted. " "Home Assistant startup has been interrupted. "
"Its state may be inconsistent" "Its state may be inconsistent"
@ -824,7 +824,7 @@ class HomeAssistant:
def stop(self) -> None: def stop(self) -> None:
"""Stop Home Assistant and shuts down all threads.""" """Stop Home Assistant and shuts down all threads."""
if self.state == CoreState.not_running: # just ignore if self.state is CoreState.not_running: # just ignore
return return
# The future is never retrieved, and we only hold a reference # The future is never retrieved, and we only hold a reference
# to it to prevent it from being garbage collected. # to it to prevent it from being garbage collected.
@ -844,12 +844,12 @@ class HomeAssistant:
if not force: if not force:
# Some tests require async_stop to run, # Some tests require async_stop to run,
# regardless of the state of the loop. # regardless of the state of the loop.
if self.state == CoreState.not_running: # just ignore if self.state is CoreState.not_running: # just ignore
return return
if self.state in [CoreState.stopping, CoreState.final_write]: if self.state in [CoreState.stopping, CoreState.final_write]:
_LOGGER.info("Additional call to async_stop was ignored") _LOGGER.info("Additional call to async_stop was ignored")
return return
if self.state == CoreState.starting: if self.state is CoreState.starting:
# This may not work # This may not work
_LOGGER.warning( _LOGGER.warning(
"Stopping Home Assistant before startup has completed may fail" "Stopping Home Assistant before startup has completed may fail"

View file

@ -23,7 +23,7 @@ def async_create_flow(
dispatcher: FlowDispatcher | None = None dispatcher: FlowDispatcher | None = None
if DISCOVERY_FLOW_DISPATCHER in hass.data: if DISCOVERY_FLOW_DISPATCHER in hass.data:
dispatcher = hass.data[DISCOVERY_FLOW_DISPATCHER] dispatcher = hass.data[DISCOVERY_FLOW_DISPATCHER]
elif hass.state != CoreState.running: elif hass.state is not CoreState.running:
dispatcher = hass.data[DISCOVERY_FLOW_DISPATCHER] = FlowDispatcher(hass) dispatcher = hass.data[DISCOVERY_FLOW_DISPATCHER] = FlowDispatcher(hass)
dispatcher.async_setup() dispatcher.async_setup()

View file

@ -401,7 +401,7 @@ class EntityPlatform:
self._async_cancel_retry_setup = None self._async_cancel_retry_setup = None
await self._async_setup_platform(async_create_setup_task, tries) await self._async_setup_platform(async_create_setup_task, tries)
if hass.state == CoreState.running: if hass.state is CoreState.running:
self._async_cancel_retry_setup = async_call_later( self._async_cancel_retry_setup = async_call_later(
hass, wait_time, setup_again hass, wait_time, setup_again
) )

View file

@ -81,7 +81,7 @@ def async_at_started(
""" """
def _is_started(hass: HomeAssistant) -> bool: def _is_started(hass: HomeAssistant) -> bool:
return hass.state == CoreState.running return hass.state is CoreState.running
return _async_at_core_state( return _async_at_core_state(
hass, at_start_cb, EVENT_HOMEASSISTANT_STARTED, _is_started hass, at_start_cb, EVENT_HOMEASSISTANT_STARTED, _is_started

View file

@ -260,7 +260,7 @@ class Store(Generic[_T]):
"data": data, "data": data,
} }
if self.hass.state == CoreState.stopping: if self.hass.state is CoreState.stopping:
self._async_ensure_final_write_listener() self._async_ensure_final_write_listener()
return return
@ -286,7 +286,7 @@ class Store(Generic[_T]):
self._async_cleanup_delay_listener() self._async_cleanup_delay_listener()
self._async_ensure_final_write_listener() self._async_ensure_final_write_listener()
if self.hass.state == CoreState.stopping: if self.hass.state is CoreState.stopping:
return return
self._unsub_delay_listener = async_call_later( self._unsub_delay_listener = async_call_later(
@ -318,7 +318,7 @@ class Store(Generic[_T]):
async def _async_callback_delayed_write(self, _now): async def _async_callback_delayed_write(self, _now):
"""Handle a delayed write callback.""" """Handle a delayed write callback."""
# catch the case where a call is scheduled and then we stop Home Assistant # catch the case where a call is scheduled and then we stop Home Assistant
if self.hass.state == CoreState.stopping: if self.hass.state is CoreState.stopping:
self._async_ensure_final_write_listener() self._async_ensure_final_write_listener()
return return
await self._async_handle_write_data() await self._async_handle_write_data()

View file

@ -818,7 +818,7 @@ async def test_this_variable_early_hass_running(
""" """
# Start hass # Start hass
assert hass.state == CoreState.running assert hass.state is CoreState.running
await hass.async_start() await hass.async_start()
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -1509,7 +1509,7 @@ async def async_setup_recorder_instance(
await hass.async_block_till_done() await hass.async_block_till_done()
instance = hass.data[recorder.DATA_INSTANCE] instance = hass.data[recorder.DATA_INSTANCE]
# The recorder's worker is not started until Home Assistant is running # The recorder's worker is not started until Home Assistant is running
if hass.state == CoreState.running: if hass.state is CoreState.running:
await async_recorder_block_till_done(hass) await async_recorder_block_till_done(hass)
return instance return instance

View file

@ -8,7 +8,7 @@ from homeassistant.helpers import start
async def test_at_start_when_running_awaitable(hass: HomeAssistant) -> None: async def test_at_start_when_running_awaitable(hass: HomeAssistant) -> None:
"""Test at start when already running.""" """Test at start when already running."""
assert hass.state == CoreState.running assert hass.state is CoreState.running
assert hass.is_running assert hass.is_running
calls = [] calls = []
@ -33,7 +33,7 @@ async def test_at_start_when_running_callback(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None: ) -> None:
"""Test at start when already running.""" """Test at start when already running."""
assert hass.state == CoreState.running assert hass.state is CoreState.running
assert hass.is_running assert hass.is_running
calls = [] calls = []
@ -110,7 +110,7 @@ async def test_cancelling_at_start_when_running(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None: ) -> None:
"""Test cancelling at start when already running.""" """Test cancelling at start when already running."""
assert hass.state == CoreState.running assert hass.state is CoreState.running
assert hass.is_running assert hass.is_running
calls = [] calls = []
@ -151,7 +151,7 @@ async def test_cancelling_at_start_when_starting(hass: HomeAssistant) -> None:
async def test_at_started_when_running_awaitable(hass: HomeAssistant) -> None: async def test_at_started_when_running_awaitable(hass: HomeAssistant) -> None:
"""Test at started when already started.""" """Test at started when already started."""
assert hass.state == CoreState.running assert hass.state is CoreState.running
calls = [] calls = []
@ -175,7 +175,7 @@ async def test_at_started_when_running_callback(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None: ) -> None:
"""Test at started when already running.""" """Test at started when already running."""
assert hass.state == CoreState.running assert hass.state is CoreState.running
calls = [] calls = []
@ -257,7 +257,7 @@ async def test_cancelling_at_started_when_running(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None: ) -> None:
"""Test cancelling at start when already running.""" """Test cancelling at start when already running."""
assert hass.state == CoreState.running assert hass.state is CoreState.running
assert hass.is_running assert hass.is_running
calls = [] calls = []

View file

@ -413,7 +413,7 @@ async def test_stage_shutdown_timeouts(hass: HomeAssistant) -> None:
with patch.object(hass.timeout, "async_timeout", side_effect=asyncio.TimeoutError): with patch.object(hass.timeout, "async_timeout", side_effect=asyncio.TimeoutError):
await hass.async_stop() await hass.async_stop()
assert hass.state == CoreState.stopped assert hass.state is CoreState.stopped
async def test_stage_shutdown_generic_error(hass: HomeAssistant, caplog) -> None: async def test_stage_shutdown_generic_error(hass: HomeAssistant, caplog) -> None: