Skip to content

Commit

Permalink
Use assignment expressions 43 - WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p committed Dec 10, 2024
1 parent 35ecca5 commit 7ef6453
Show file tree
Hide file tree
Showing 95 changed files with 131 additions and 255 deletions.
3 changes: 1 addition & 2 deletions homeassistant/components/analytics/analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,7 @@ def supervisor(self) -> bool:

async def load(self) -> None:
"""Load preferences."""
stored = await self._store.async_load()
if stored:
if stored := await self._store.async_load():
self._data = AnalyticsData.from_dict(stored)

if (
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/androidtv_remote/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@ async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the Android TV on."""
if not self.is_on:
self._send_key_command("POWER")
activity = kwargs.get(ATTR_ACTIVITY, "")
if activity:
if activity := kwargs.get(ATTR_ACTIVITY, ""):
activity = next(
(
app_id
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/application_credentials/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,7 @@ async def _async_provide_implementation(
) -> list[config_entry_oauth2_flow.AbstractOAuth2Implementation]:
"""Return registered OAuth implementations."""

platform = await _get_platform(hass, domain)
if not platform:
if not (platform := await _get_platform(hass, domain)):
return []

credentials = hass.data[DATA_COMPONENT].async_client_credentials(domain)
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/assist_pipeline/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ def get_vad_sensitivity(
if sensitivity_entity_id is None:
return VadSensitivity.DEFAULT

state = hass.states.get(sensitivity_entity_id)
if state is None:
if (state := hass.states.get(sensitivity_entity_id)) is None:
return VadSensitivity.DEFAULT

return VadSensitivity(state.state)
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/automation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1180,9 +1180,7 @@ def websocket_config(
msg: dict[str, Any],
) -> None:
"""Get automation config."""
automation = hass.data[DATA_COMPONENT].get_entity(msg["entity_id"])

if automation is None:
if (automation := hass.data[DATA_COMPONENT].get_entity(msg["entity_id"])) is None:
connection.send_error(
msg["id"], websocket_api.ERR_NOT_FOUND, "Entity not found"
)
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/camera/media_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ def __init__(self, hass: HomeAssistant) -> None:
async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
"""Resolve media to a url."""
component = self.hass.data[DATA_COMPONENT]
camera = component.get_entity(item.identifier)

if not camera:
if not (camera := component.get_entity(item.identifier)):
raise Unresolvable(f"Could not resolve media item: {item.identifier}")

if not (stream_types := camera.camera_capabilities.frontend_stream_types):
Expand Down Expand Up @@ -95,8 +94,7 @@ async def async_browse_media(
can_stream_hls = "stream" in self.hass.config.components

async def _filter_browsable_camera(camera: Camera) -> BrowseMediaSource | None:
stream_types = camera.camera_capabilities.frontend_stream_types
if not stream_types:
if not (stream_types := camera.camera_capabilities.frontend_stream_types):
return _media_source_for_camera(self.hass, camera, camera.content_type)
if not can_stream_hls:
return None
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/cloud/http_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -639,9 +639,8 @@ async def google_assistant_get(
cloud = hass.data[DATA_CLOUD]
gconf = await cloud.client.get_google_config()
entity_id: str = msg["entity_id"]
state = hass.states.get(entity_id)

if not state:
if not (state := hass.states.get(entity_id)):
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/config/config_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,7 @@ async def post(self, request: web.Request, entry_id: str) -> web.Response:
raise Unauthorized(config_entry_id=entry_id, permission="remove")

hass = request.app[KEY_HASS]
entry = hass.config_entries.async_get_entry(entry_id)
if not entry:
if not (entry := hass.config_entries.async_get_entry(entry_id)):
return self.json_message("Invalid entry specified", HTTPStatus.NOT_FOUND)
assert isinstance(entry, config_entries.ConfigEntry)

Expand Down
1 change: 0 additions & 1 deletion homeassistant/components/cups/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ def setup_platform(
printers: list[str] = config[CONF_PRINTERS]
is_cups: bool = config[CONF_IS_CUPS_SERVER]

# pylint: disable-next=consider-using-assignment-expr
if is_cups:
data = CupsData(host, port, None)
data.update()
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/demo/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,7 @@ def _async_bump_sum(self, now: datetime) -> None:
async def async_added_to_hass(self) -> None:
"""Call when entity about to be added to hass."""
await super().async_added_to_hass()
state = await self.async_get_last_sensor_data()
if state:
if state := await self.async_get_last_sensor_data():
self._attr_native_value = cast(float, state.native_value)

self.async_on_remove(
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/derivative/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,7 @@ def __init__(
async def async_added_to_hass(self) -> None:
"""Handle entity which will be added."""
await super().async_added_to_hass()
restored_data = await self.async_get_last_sensor_data()
if restored_data:
if restored_data := await self.async_get_last_sensor_data():
self._attr_native_unit_of_measurement = (
restored_data.native_unit_of_measurement
)
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/device_automation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,8 +332,7 @@ def async_get_entity_registry_entry_or_raise(
) -> er.RegistryEntry:
"""Get an entity registry entry from entry ID or raise."""
entity_registry = er.async_get(hass)
entry = entity_registry.async_get(entity_registry_id)
if entry is None:
if (entry := entity_registry.async_get(entity_registry_id)) is None:
raise EntityNotFound
return entry

Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/dlna_dmr/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,8 +443,7 @@ def _is_dmr_device(discovery_info: ssdp.SsdpServiceInfo) -> bool:
if not discovery_service_list:
return False

services = discovery_service_list.get("service")
if not services:
if not (services := discovery_service_list.get("service")):
discovery_service_ids: set[str] = set()
elif isinstance(services, list):
discovery_service_ids = {service.get("serviceId") for service in services}
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/dlna_dms/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ async def async_step_ssdp(
if not discovery_service_list:
return self.async_abort(reason="not_dms")

services = discovery_service_list.get("service")
if not services:
if not (services := discovery_service_list.get("service")):
discovery_service_ids: set[str] = set()
elif isinstance(services, list):
discovery_service_ids = {service.get("serviceId") for service in services}
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/dynalite/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ async def async_added_to_hass(self) -> None:
# register for device specific update
await super().async_added_to_hass()

cur_state = await self.async_get_last_state()
if cur_state:
if cur_state := await self.async_get_last_state():
self.initialize_state(cur_state)
else:
LOGGER.warning("Restore state not available for %s", self.entity_id)
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/dynalite/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ def save_dynalite_config(
) -> None:
"""Retrieve the Dynalite config for the frontend."""
entry_id = msg["entry_id"]
entry = hass.config_entries.async_get_entry(entry_id)
if not entry:
if not (entry := hass.config_entries.async_get_entry(entry_id)):
LOGGER.error(
"Dynalite - received updated config for invalid entry - %s", entry_id
)
Expand Down
36 changes: 16 additions & 20 deletions homeassistant/components/edl21/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,9 +340,7 @@ def event(self, message_body) -> None:
assert isinstance(message_body, SmlGetListResponse)
LOGGER.debug("Received sml message on %s: %s", self._serial_port, message_body)

electricity_id = message_body["serverId"]

if electricity_id is None:
if (electricity_id := message_body["serverId"]) is None:
LOGGER.debug(
"No electricity id found in sml message on %s", self._serial_port
)
Expand All @@ -358,25 +356,23 @@ def event(self, message_body) -> None:
async_dispatcher_send(
self._hass, SIGNAL_EDL21_TELEGRAM, electricity_id, telegram
)
else:
entity_description = SENSORS.get(obis)
if entity_description:
new_entities.append(
EDL21Entity(
electricity_id,
obis,
entity_description,
telegram,
)
)
self._registered_obis.add((electricity_id, obis))
elif obis not in self._OBIS_BLACKLIST:
LOGGER.warning(
"Unhandled sensor %s detected. Please report at %s",
elif entity_description := SENSORS.get(obis):
new_entities.append(
EDL21Entity(
electricity_id,
obis,
"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+edl21%22",
entity_description,
telegram,
)
self._OBIS_BLACKLIST.add(obis)
)
self._registered_obis.add((electricity_id, obis))
elif obis not in self._OBIS_BLACKLIST:
LOGGER.warning(
"Unhandled sensor %s detected. Please report at %s",
obis,
"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+edl21%22",
)
self._OBIS_BLACKLIST.add(obis)

if new_entities:
self._async_add_entities(new_entities, update_before_add=True)
Expand Down
10 changes: 5 additions & 5 deletions homeassistant/components/elkm1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,11 +296,11 @@ def _keypad_changed(keypad: Element, changeset: dict[str, Any]) -> None:
except TimeoutError as exc:
raise ConfigEntryNotReady(f"Timed out connecting to {conf[CONF_HOST]}") from exc

elk_temp_unit = elk.panel.temperature_units
if elk_temp_unit == "C":
temperature_unit = UnitOfTemperature.CELSIUS
else:
temperature_unit = UnitOfTemperature.FAHRENHEIT
temperature_unit = (
UnitOfTemperature.CELSIUS
if elk.panel.temperature_units == "C"
else UnitOfTemperature.FAHRENHEIT
)
config["temperature_unit"] = temperature_unit
prefix: str = conf[CONF_PREFIX]
auto_configure: bool = conf[CONF_AUTO_CONFIGURE]
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/escea/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ async def wrap_and_catch(self, coro: Coroutine) -> None:

async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
temp = kwargs.get(ATTR_TEMPERATURE)
if temp is not None:
if (temp := kwargs.get(ATTR_TEMPERATURE)) is not None:
await self.wrap_and_catch(self._controller.set_desired_temp(temp))

async def async_set_fan_mode(self, fan_mode: str) -> None:
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/escea/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ async def async_start_discovery_service(
hass: HomeAssistant,
) -> AbstractDiscoveryService:
"""Set up the pescea internal discovery."""
discovery_service = hass.data.get(DATA_DISCOVERY_SERVICE)
if discovery_service:
if discovery_service := hass.data.get(DATA_DISCOVERY_SERVICE):
# Already started
return discovery_service

Expand All @@ -68,8 +67,7 @@ async def async_start_discovery_service(

async def async_stop_discovery_service(hass: HomeAssistant) -> None:
"""Stop the discovery service."""
discovery_service = hass.data.get(DATA_DISCOVERY_SERVICE)
if not discovery_service:
if not (discovery_service := hass.data.get(DATA_DISCOVERY_SERVICE)):
return

await discovery_service.close()
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/esphome/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,9 +462,7 @@ async def _retrieve_encryption_key_from_dashboard(self) -> bool:
if not dashboard.last_update_success:
return False

device = dashboard.data.get(self._device_name)

if device is None:
if (device := dashboard.data.get(self._device_name)) is None:
return False

try:
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/forked_daapd/browse_media.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,7 @@ async def get_owntone_content(
# Query API for next level
if media_content.type == MEDIA_TYPE_DIRECTORY:
# returns tracks, directories, and playlists
directory_path = media_content.id_or_path
if directory_path:
if directory_path := media_content.id_or_path:
result = await master.api.get_directory(directory=directory_path)
else:
result = await master.api.get_directory()
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/frontier_silicon/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ async def async_step_ssdp(
) -> ConfigFlowResult:
"""Process entity discovered via SSDP."""

device_url = discovery_info.ssdp_location
if device_url is None:
if (device_url := discovery_info.ssdp_location) is None:
return self.async_abort(reason="cannot_connect")

device_hostname = hostname_from_url(device_url)
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/fully_kiosk/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@ async def collect_coordinators(
config_entries = list[ConfigEntry]()
registry = dr.async_get(hass)
for target in device_ids:
device = registry.async_get(target)
if device:
if device := registry.async_get(target):
device_entries = list[ConfigEntry]()
for entry_id in device.config_entries:
entry = hass.config_entries.async_get_entry(entry_id)
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/google_assistant_sdk/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ async def async_send_message(self, message: str = "", **kwargs: Any) -> None:
)

commands: list[str] = []
targets = kwargs.get(ATTR_TARGET)
if not targets:
if not (targets := kwargs.get(ATTR_TARGET)):
commands.append(broadcast_commands(language_code)[0].format(message))
else:
commands.extend(
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/history/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ def entities_may_have_state_changes_after(
) -> bool:
"""Check the state machine to see if entities have changed since start time."""
for entity_id in entity_ids:
state = hass.states.get(entity_id)
if state is None:
if (state := hass.states.get(entity_id)) is None:
return True

state_time = state.last_changed if no_attributes else state.last_updated
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/home_connect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,10 @@ async def _async_service_program(call, method):

options = []

option_key = call.data.get(ATTR_KEY)
if option_key is not None:
if (option_key := call.data.get(ATTR_KEY)) is not None:
option = {ATTR_KEY: option_key, ATTR_VALUE: call.data[ATTR_VALUE]}

option_unit = call.data.get(ATTR_UNIT)
if option_unit is not None:
if (option_unit := call.data.get(ATTR_UNIT)) is not None:
option[ATTR_UNIT] = option_unit

options.append(option)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,9 +225,7 @@ def async_set_channel(self, channel: int) -> None:

async def async_load(self) -> None:
"""Load the store."""
data = await self._store.async_load()

if data is not None:
if (data := await self._store.async_load()) is not None:
self._channel = data["channel"]

@callback
Expand Down
12 changes: 4 additions & 8 deletions homeassistant/components/homekit/type_sensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,7 @@ def create_services(self) -> None:
@callback
def async_update_state(self, new_state: State) -> None:
"""Update accessory after state change."""
density = convert_to_float(new_state.state)
if density is None:
if (density := convert_to_float(new_state.state)) is None:
return
if self.char_density.value != density:
self.char_density.set_value(density)
Expand All @@ -246,8 +245,7 @@ def create_services(self) -> None:
@callback
def async_update_state(self, new_state: State) -> None:
"""Update accessory after state change."""
density = convert_to_float(new_state.state)
if density is None:
if (density := convert_to_float(new_state.state)) is None:
return
if self.char_density.value != density:
self.char_density.set_value(density)
Expand Down Expand Up @@ -275,8 +273,7 @@ def create_services(self) -> None:
@callback
def async_update_state(self, new_state: State) -> None:
"""Update accessory after state change."""
density = convert_to_float(new_state.state)
if density is None:
if (density := convert_to_float(new_state.state)) is None:
return
if self.char_density.value != density:
self.char_density.set_value(density)
Expand Down Expand Up @@ -312,8 +309,7 @@ def create_services(self) -> None:
@callback
def async_update_state(self, new_state: State) -> None:
"""Update accessory after state change."""
density = convert_to_float(new_state.state)
if density is None:
if (density := convert_to_float(new_state.state)) is None:
return
if self.char_density.value != density:
self.char_density.set_value(density)
Expand Down
Loading

0 comments on commit 7ef6453

Please sign in to comment.