mirror of
https://github.com/home-assistant/core.git
synced 2025-07-23 21:27:38 +00:00
Use assignment expressions 30 (#58714)
This commit is contained in:
parent
7063c05127
commit
84618fa831
@ -125,8 +125,7 @@ class ArubaDeviceScanner(DeviceScanner):
|
|||||||
|
|
||||||
devices = {}
|
devices = {}
|
||||||
for device in devices_result:
|
for device in devices_result:
|
||||||
match = _DEVICES_REGEX.search(device.decode("utf-8"))
|
if match := _DEVICES_REGEX.search(device.decode("utf-8")):
|
||||||
if match:
|
|
||||||
devices[match.group("ip")] = {
|
devices[match.group("ip")] = {
|
||||||
"ip": match.group("ip"),
|
"ip": match.group("ip"),
|
||||||
"mac": match.group("mac").upper(),
|
"mac": match.group("mac").upper(),
|
||||||
|
@ -156,9 +156,7 @@ def entities_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]:
|
|||||||
|
|
||||||
component = hass.data[DOMAIN]
|
component = hass.data[DOMAIN]
|
||||||
|
|
||||||
automation_entity = component.get_entity(entity_id)
|
if (automation_entity := component.get_entity(entity_id)) is None:
|
||||||
|
|
||||||
if automation_entity is None:
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
return list(automation_entity.referenced_entities)
|
return list(automation_entity.referenced_entities)
|
||||||
@ -187,9 +185,7 @@ def devices_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]:
|
|||||||
|
|
||||||
component = hass.data[DOMAIN]
|
component = hass.data[DOMAIN]
|
||||||
|
|
||||||
automation_entity = component.get_entity(entity_id)
|
if (automation_entity := component.get_entity(entity_id)) is None:
|
||||||
|
|
||||||
if automation_entity is None:
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
return list(automation_entity.referenced_devices)
|
return list(automation_entity.referenced_devices)
|
||||||
@ -218,9 +214,7 @@ def areas_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]:
|
|||||||
|
|
||||||
component = hass.data[DOMAIN]
|
component = hass.data[DOMAIN]
|
||||||
|
|
||||||
automation_entity = component.get_entity(entity_id)
|
if (automation_entity := component.get_entity(entity_id)) is None:
|
||||||
|
|
||||||
if automation_entity is None:
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
return list(automation_entity.referenced_areas)
|
return list(automation_entity.referenced_areas)
|
||||||
|
@ -180,8 +180,7 @@ class BondLight(BondBaseLight, BondEntity, LightEntity):
|
|||||||
|
|
||||||
async def async_turn_on(self, **kwargs: Any) -> None:
|
async def async_turn_on(self, **kwargs: Any) -> None:
|
||||||
"""Turn on the light."""
|
"""Turn on the light."""
|
||||||
brightness = kwargs.get(ATTR_BRIGHTNESS)
|
if brightness := kwargs.get(ATTR_BRIGHTNESS):
|
||||||
if brightness:
|
|
||||||
await self._hub.bond.action(
|
await self._hub.bond.action(
|
||||||
self._device.device_id,
|
self._device.device_id,
|
||||||
Action.set_brightness(round((brightness * 100) / 255)),
|
Action.set_brightness(round((brightness * 100) / 255)),
|
||||||
|
@ -275,9 +275,7 @@ def _get_camera_from_entity_id(hass: HomeAssistant, entity_id: str) -> Camera:
|
|||||||
if (component := hass.data.get(DOMAIN)) is None:
|
if (component := hass.data.get(DOMAIN)) is None:
|
||||||
raise HomeAssistantError("Camera integration not set up")
|
raise HomeAssistantError("Camera integration not set up")
|
||||||
|
|
||||||
camera = component.get_entity(entity_id)
|
if (camera := component.get_entity(entity_id)) is None:
|
||||||
|
|
||||||
if camera is None:
|
|
||||||
raise HomeAssistantError("Camera not found")
|
raise HomeAssistantError("Camera not found")
|
||||||
|
|
||||||
if not camera.is_on:
|
if not camera.is_on:
|
||||||
@ -596,9 +594,7 @@ class CameraView(HomeAssistantView):
|
|||||||
|
|
||||||
async def get(self, request: web.Request, entity_id: str) -> web.StreamResponse:
|
async def get(self, request: web.Request, entity_id: str) -> web.StreamResponse:
|
||||||
"""Start a GET request."""
|
"""Start a GET request."""
|
||||||
camera = self.component.get_entity(entity_id)
|
if (camera := self.component.get_entity(entity_id)) is None:
|
||||||
|
|
||||||
if camera is None:
|
|
||||||
raise web.HTTPNotFound()
|
raise web.HTTPNotFound()
|
||||||
|
|
||||||
camera = cast(Camera, camera)
|
camera = cast(Camera, camera)
|
||||||
|
@ -81,8 +81,7 @@ class DlnaDmrFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
LOGGER.debug("async_step_user: user_input: %s", user_input)
|
LOGGER.debug("async_step_user: user_input: %s", user_input)
|
||||||
|
|
||||||
if user_input is not None:
|
if user_input is not None:
|
||||||
host = user_input.get(CONF_HOST)
|
if not (host := user_input.get(CONF_HOST)):
|
||||||
if not host:
|
|
||||||
# No device chosen, user might want to directly enter an URL
|
# No device chosen, user might want to directly enter an URL
|
||||||
return await self.async_step_manual()
|
return await self.async_step_manual()
|
||||||
# User has chosen a device, ask for confirmation
|
# User has chosen a device, ask for confirmation
|
||||||
|
@ -613,8 +613,7 @@ class DlnaDmrEntity(MediaPlayerEntity):
|
|||||||
metadata: dict[str, Any] = extra.get("metadata") or {}
|
metadata: dict[str, Any] = extra.get("metadata") or {}
|
||||||
|
|
||||||
title = extra.get("title") or metadata.get("title") or "Home Assistant"
|
title = extra.get("title") or metadata.get("title") or "Home Assistant"
|
||||||
thumb = extra.get("thumb")
|
if thumb := extra.get("thumb"):
|
||||||
if thumb:
|
|
||||||
metadata["album_art_uri"] = thumb
|
metadata["album_art_uri"] = thumb
|
||||||
|
|
||||||
# Translate metadata keys from HA names to DIDL-Lite names
|
# Translate metadata keys from HA names to DIDL-Lite names
|
||||||
@ -666,8 +665,7 @@ class DlnaDmrEntity(MediaPlayerEntity):
|
|||||||
if not self._device:
|
if not self._device:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
play_mode = self._device.play_mode
|
if not (play_mode := self._device.play_mode):
|
||||||
if not play_mode:
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if play_mode == PlayMode.VENDOR_DEFINED:
|
if play_mode == PlayMode.VENDOR_DEFINED:
|
||||||
@ -700,8 +698,7 @@ class DlnaDmrEntity(MediaPlayerEntity):
|
|||||||
if not self._device:
|
if not self._device:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
play_mode = self._device.play_mode
|
if not (play_mode := self._device.play_mode):
|
||||||
if not play_mode:
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if play_mode == PlayMode.VENDOR_DEFINED:
|
if play_mode == PlayMode.VENDOR_DEFINED:
|
||||||
|
@ -182,9 +182,7 @@ class HangoutsBot:
|
|||||||
"""Detect a matching intent."""
|
"""Detect a matching intent."""
|
||||||
for intent_type, data in intents.items():
|
for intent_type, data in intents.items():
|
||||||
for matcher in data.get(CONF_MATCHERS, []):
|
for matcher in data.get(CONF_MATCHERS, []):
|
||||||
match = matcher.match(text)
|
if not (match := matcher.match(text)):
|
||||||
|
|
||||||
if not match:
|
|
||||||
continue
|
continue
|
||||||
if intent_type == INTENT_HELP:
|
if intent_type == INTENT_HELP:
|
||||||
return await self.hass.helpers.intent.async_handle(
|
return await self.hass.helpers.intent.async_handle(
|
||||||
|
@ -75,8 +75,7 @@ def ensure_pin_format(pin, allow_insecure_setup_codes=None):
|
|||||||
|
|
||||||
If incorrect code is entered, an exception is raised.
|
If incorrect code is entered, an exception is raised.
|
||||||
"""
|
"""
|
||||||
match = PIN_FORMAT.search(pin.strip())
|
if not (match := PIN_FORMAT.search(pin.strip())):
|
||||||
if not match:
|
|
||||||
raise aiohomekit.exceptions.MalformedPinError(f"Invalid PIN code f{pin}")
|
raise aiohomekit.exceptions.MalformedPinError(f"Invalid PIN code f{pin}")
|
||||||
pin_without_dashes = "".join(match.groups())
|
pin_without_dashes = "".join(match.groups())
|
||||||
if not allow_insecure_setup_codes and pin_without_dashes in INSECURE_CODES:
|
if not allow_insecure_setup_codes and pin_without_dashes in INSECURE_CODES:
|
||||||
|
@ -304,10 +304,8 @@ async def async_update_device_config(
|
|||||||
device_connection: DeviceConnectionType, device_config: ConfigType
|
device_connection: DeviceConnectionType, device_config: ConfigType
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Fill missing values in device_config with infos from LCN bus."""
|
"""Fill missing values in device_config with infos from LCN bus."""
|
||||||
is_group = device_config[CONF_ADDRESS][2]
|
|
||||||
|
|
||||||
# fetch serial info if device is module
|
# fetch serial info if device is module
|
||||||
if not is_group: # is module
|
if not (is_group := device_config[CONF_ADDRESS][2]): # is module
|
||||||
await device_connection.serial_known
|
await device_connection.serial_known
|
||||||
if device_config[CONF_HARDWARE_SERIAL] == -1:
|
if device_config[CONF_HARDWARE_SERIAL] == -1:
|
||||||
device_config[CONF_HARDWARE_SERIAL] = device_connection.hardware_serial
|
device_config[CONF_HARDWARE_SERIAL] = device_connection.hardware_serial
|
||||||
|
@ -193,9 +193,7 @@ class LogbookView(HomeAssistantView):
|
|||||||
async def get(self, request, datetime=None):
|
async def get(self, request, datetime=None):
|
||||||
"""Retrieve logbook entries."""
|
"""Retrieve logbook entries."""
|
||||||
if datetime:
|
if datetime:
|
||||||
datetime = dt_util.parse_datetime(datetime)
|
if (datetime := dt_util.parse_datetime(datetime)) is None:
|
||||||
|
|
||||||
if datetime is None:
|
|
||||||
return self.json_message("Invalid datetime", HTTPStatus.BAD_REQUEST)
|
return self.json_message("Invalid datetime", HTTPStatus.BAD_REQUEST)
|
||||||
else:
|
else:
|
||||||
datetime = dt_util.start_of_local_day()
|
datetime = dt_util.start_of_local_day()
|
||||||
@ -219,8 +217,7 @@ class LogbookView(HomeAssistantView):
|
|||||||
end_day = start_day + timedelta(days=period)
|
end_day = start_day + timedelta(days=period)
|
||||||
else:
|
else:
|
||||||
start_day = datetime
|
start_day = datetime
|
||||||
end_day = dt_util.parse_datetime(end_time)
|
if (end_day := dt_util.parse_datetime(end_time)) is None:
|
||||||
if end_day is None:
|
|
||||||
return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST)
|
return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST)
|
||||||
|
|
||||||
hass = request.app["hass"]
|
hass = request.app["hass"]
|
||||||
|
@ -1026,8 +1026,7 @@ class MediaPlayerImageView(HomeAssistantView):
|
|||||||
media_content_id: str | None = None,
|
media_content_id: str | None = None,
|
||||||
) -> web.Response:
|
) -> web.Response:
|
||||||
"""Start a get request."""
|
"""Start a get request."""
|
||||||
player = self.component.get_entity(entity_id)
|
if (player := self.component.get_entity(entity_id)) is None:
|
||||||
if player is None:
|
|
||||||
status = (
|
status = (
|
||||||
HTTPStatus.NOT_FOUND
|
HTTPStatus.NOT_FOUND
|
||||||
if request[KEY_AUTHENTICATED]
|
if request[KEY_AUTHENTICATED]
|
||||||
@ -1071,9 +1070,8 @@ async def websocket_handle_thumbnail(hass, connection, msg):
|
|||||||
Async friendly.
|
Async friendly.
|
||||||
"""
|
"""
|
||||||
component = hass.data[DOMAIN]
|
component = hass.data[DOMAIN]
|
||||||
player = component.get_entity(msg["entity_id"])
|
|
||||||
|
|
||||||
if player is None:
|
if (player := component.get_entity(msg["entity_id"])) is None:
|
||||||
connection.send_message(
|
connection.send_message(
|
||||||
websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found")
|
websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found")
|
||||||
)
|
)
|
||||||
|
@ -93,9 +93,7 @@ class MediaSourceItem:
|
|||||||
@classmethod
|
@classmethod
|
||||||
def from_uri(cls, hass: HomeAssistant, uri: str) -> MediaSourceItem:
|
def from_uri(cls, hass: HomeAssistant, uri: str) -> MediaSourceItem:
|
||||||
"""Create an item from a uri."""
|
"""Create an item from a uri."""
|
||||||
match = URI_SCHEME_REGEX.match(uri)
|
if not (match := URI_SCHEME_REGEX.match(uri)):
|
||||||
|
|
||||||
if not match:
|
|
||||||
raise ValueError("Invalid media source URI")
|
raise ValueError("Invalid media source URI")
|
||||||
|
|
||||||
domain = match.group("domain")
|
domain = match.group("domain")
|
||||||
|
@ -130,8 +130,7 @@ class MelCloudDevice:
|
|||||||
def device_info(self) -> DeviceInfo:
|
def device_info(self) -> DeviceInfo:
|
||||||
"""Return a device description for device registry."""
|
"""Return a device description for device registry."""
|
||||||
model = None
|
model = None
|
||||||
unit_infos = self.device.units
|
if (unit_infos := self.device.units) is not None:
|
||||||
if unit_infos is not None:
|
|
||||||
model = ", ".join([x["model"] for x in unit_infos if x["model"]])
|
model = ", ".join([x["model"] for x in unit_infos if x["model"]])
|
||||||
return DeviceInfo(
|
return DeviceInfo(
|
||||||
connections={(CONNECTION_NETWORK_MAC, self.device.mac)},
|
connections={(CONNECTION_NETWORK_MAC, self.device.mac)},
|
||||||
|
@ -68,8 +68,7 @@ class OctoPrintBinarySensorBase(CoordinatorEntity, BinarySensorEntity):
|
|||||||
@property
|
@property
|
||||||
def is_on(self):
|
def is_on(self):
|
||||||
"""Return true if binary sensor is on."""
|
"""Return true if binary sensor is on."""
|
||||||
printer = self.coordinator.data["printer"]
|
if not (printer := self.coordinator.data["printer"]):
|
||||||
if not printer:
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return bool(self._get_flag_state(printer))
|
return bool(self._get_flag_state(printer))
|
||||||
|
@ -130,8 +130,7 @@ class OctoPrintJobPercentageSensor(OctoPrintSensorBase):
|
|||||||
if not job:
|
if not job:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
state = job.progress.completion
|
if not (state := job.progress.completion):
|
||||||
if not state:
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
return round(state, 2)
|
return round(state, 2)
|
||||||
|
@ -274,8 +274,7 @@ class PandoraMediaPlayer(MediaPlayerEntity):
|
|||||||
|
|
||||||
def _update_current_station(self, response):
|
def _update_current_station(self, response):
|
||||||
"""Update current station."""
|
"""Update current station."""
|
||||||
station_match = re.search(STATION_PATTERN, response)
|
if station_match := re.search(STATION_PATTERN, response):
|
||||||
if station_match:
|
|
||||||
self._station = station_match.group(1)
|
self._station = station_match.group(1)
|
||||||
_LOGGER.debug("Got station as: %s", self._station)
|
_LOGGER.debug("Got station as: %s", self._station)
|
||||||
else:
|
else:
|
||||||
@ -283,8 +282,7 @@ class PandoraMediaPlayer(MediaPlayerEntity):
|
|||||||
|
|
||||||
def _update_current_song(self, response):
|
def _update_current_song(self, response):
|
||||||
"""Update info about current song."""
|
"""Update info about current song."""
|
||||||
song_match = re.search(CURRENT_SONG_PATTERN, response)
|
if song_match := re.search(CURRENT_SONG_PATTERN, response):
|
||||||
if song_match:
|
|
||||||
(
|
(
|
||||||
self._media_title,
|
self._media_title,
|
||||||
self._media_artist,
|
self._media_artist,
|
||||||
@ -343,8 +341,7 @@ class PandoraMediaPlayer(MediaPlayerEntity):
|
|||||||
_LOGGER.debug("Getting stations: %s", station_lines)
|
_LOGGER.debug("Getting stations: %s", station_lines)
|
||||||
self._stations = []
|
self._stations = []
|
||||||
for line in station_lines.split("\r\n"):
|
for line in station_lines.split("\r\n"):
|
||||||
match = re.search(r"\d+\).....(.+)", line)
|
if match := re.search(r"\d+\).....(.+)", line):
|
||||||
if match:
|
|
||||||
station = match.group(1).strip()
|
station = match.group(1).strip()
|
||||||
_LOGGER.debug("Found station %s", station)
|
_LOGGER.debug("Found station %s", station)
|
||||||
self._stations.append(station)
|
self._stations.append(station)
|
||||||
|
@ -620,8 +620,7 @@ def list_statistic_ids(
|
|||||||
platform_statistic_ids = platform.list_statistic_ids(hass, statistic_type)
|
platform_statistic_ids = platform.list_statistic_ids(hass, statistic_type)
|
||||||
|
|
||||||
for statistic_id, info in platform_statistic_ids.items():
|
for statistic_id, info in platform_statistic_ids.items():
|
||||||
unit = info["unit_of_measurement"]
|
if (unit := info["unit_of_measurement"]) is not None:
|
||||||
if unit is not None:
|
|
||||||
# Display unit according to user settings
|
# Display unit according to user settings
|
||||||
unit = _configured_unit(unit, units)
|
unit = _configured_unit(unit, units)
|
||||||
platform_statistic_ids[statistic_id]["unit_of_measurement"] = unit
|
platform_statistic_ids[statistic_id]["unit_of_measurement"] = unit
|
||||||
|
@ -254,8 +254,7 @@ class ToggleRflinkLight(SwitchableRflinkDevice, LightEntity):
|
|||||||
"""Adjust state if Rflink picks up a remote command for this device."""
|
"""Adjust state if Rflink picks up a remote command for this device."""
|
||||||
self.cancel_queued_send_commands()
|
self.cancel_queued_send_commands()
|
||||||
|
|
||||||
command = event["command"]
|
if event["command"] == "on":
|
||||||
if command == "on":
|
|
||||||
# if the state is unknown or false, it gets set as true
|
# if the state is unknown or false, it gets set as true
|
||||||
# if the state is true, it gets set as false
|
# if the state is true, it gets set as false
|
||||||
self._state = self._state in [None, False]
|
self._state = self._state in [None, False]
|
||||||
|
@ -81,8 +81,7 @@ def _figure_out_source(record, call_stack, hass):
|
|||||||
for pathname in reversed(stack):
|
for pathname in reversed(stack):
|
||||||
|
|
||||||
# Try to match with a file within Home Assistant
|
# Try to match with a file within Home Assistant
|
||||||
match = re.match(paths_re, pathname[0])
|
if match := re.match(paths_re, pathname[0]):
|
||||||
if match:
|
|
||||||
return [match.group(1), pathname[1]]
|
return [match.group(1), pathname[1]]
|
||||||
# Ok, we don't know what this is
|
# Ok, we don't know what this is
|
||||||
return (record.pathname, record.lineno)
|
return (record.pathname, record.lineno)
|
||||||
|
@ -398,8 +398,7 @@ class TadoClimate(TadoZoneEntity, ClimateEntity):
|
|||||||
|
|
||||||
def set_temperature(self, **kwargs):
|
def set_temperature(self, **kwargs):
|
||||||
"""Set new target temperature."""
|
"""Set new target temperature."""
|
||||||
temperature = kwargs.get(ATTR_TEMPERATURE)
|
if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:
|
||||||
if temperature is None:
|
|
||||||
return
|
return
|
||||||
|
|
||||||
if self._current_tado_hvac_mode not in (
|
if self._current_tado_hvac_mode not in (
|
||||||
|
@ -110,8 +110,7 @@ class ThomsonDeviceScanner(DeviceScanner):
|
|||||||
|
|
||||||
devices = {}
|
devices = {}
|
||||||
for device in devices_result:
|
for device in devices_result:
|
||||||
match = _DEVICES_REGEX.search(device.decode("utf-8"))
|
if match := _DEVICES_REGEX.search(device.decode("utf-8")):
|
||||||
if match:
|
|
||||||
devices[match.group("ip")] = {
|
devices[match.group("ip")] = {
|
||||||
"ip": match.group("ip"),
|
"ip": match.group("ip"),
|
||||||
"mac": match.group("mac").upper(),
|
"mac": match.group("mac").upper(),
|
||||||
|
@ -233,8 +233,7 @@ def _parse_due_date(data: dict, gmt_string) -> datetime | None:
|
|||||||
# Add time information to date only strings.
|
# Add time information to date only strings.
|
||||||
if len(data["date"]) == 10:
|
if len(data["date"]) == 10:
|
||||||
return datetime.fromisoformat(data["date"]).replace(tzinfo=dt.UTC)
|
return datetime.fromisoformat(data["date"]).replace(tzinfo=dt.UTC)
|
||||||
nowtime = dt.parse_datetime(data["date"])
|
if not (nowtime := dt.parse_datetime(data["date"])):
|
||||||
if not nowtime:
|
|
||||||
return None
|
return None
|
||||||
if nowtime.tzinfo is None:
|
if nowtime.tzinfo is None:
|
||||||
data["date"] += gmt_string
|
data["date"] += gmt_string
|
||||||
|
@ -342,9 +342,7 @@ class MusicCastMediaPlayer(MusicCastDeviceEntity, MediaPlayerEntity):
|
|||||||
parts = media_id.split(":")
|
parts = media_id.split(":")
|
||||||
|
|
||||||
if parts[0] == "list":
|
if parts[0] == "list":
|
||||||
index = parts[3]
|
if (index := parts[3]) == "-1":
|
||||||
|
|
||||||
if index == "-1":
|
|
||||||
index = "0"
|
index = "0"
|
||||||
|
|
||||||
await self.coordinator.musiccast.play_list_media(index, self._zone_id)
|
await self.coordinator.musiccast.play_list_media(index, self._zone_id)
|
||||||
|
@ -469,9 +469,7 @@ def info_from_service(service: AsyncServiceInfo) -> HaServiceInfo | None:
|
|||||||
if isinstance(value, bytes):
|
if isinstance(value, bytes):
|
||||||
properties[key] = value.decode("utf-8")
|
properties[key] = value.decode("utf-8")
|
||||||
|
|
||||||
addresses = service.addresses
|
if not (addresses := service.addresses):
|
||||||
|
|
||||||
if not addresses:
|
|
||||||
return None
|
return None
|
||||||
if (host := _first_non_link_local_or_v6_address(addresses)) is None:
|
if (host := _first_non_link_local_or_v6_address(addresses)) is None:
|
||||||
return None
|
return None
|
||||||
|
Loading…
x
Reference in New Issue
Block a user