Use assignment expressions 34 (#58823)

This commit is contained in:
Marc Mueller 2021-10-31 19:01:16 +01:00 committed by GitHub
parent e0c0d00833
commit 4c68662612
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
30 changed files with 36 additions and 75 deletions

View file

@ -137,8 +137,7 @@ class AirQualityEntity(Entity):
data: dict[str, str | int | float] = {} data: dict[str, str | int | float] = {}
for prop, attr in PROP_TO_ATTR.items(): for prop, attr in PROP_TO_ATTR.items():
value = getattr(self, prop) if (value := getattr(self, prop)) is not None:
if value is not None:
data[attr] = value data[attr] = value
return data return data

View file

@ -92,8 +92,7 @@ async def async_setup(hass, config):
return True return True
# remove not required config keys # remove not required config keys
pub_key = conf.pop(CONF_PUB_KEY, "") if pub_key := conf.pop(CONF_PUB_KEY, ""):
if pub_key:
conf[CONF_SSH_KEY] = pub_key conf[CONF_SSH_KEY] = pub_key
conf.pop(CONF_REQUIRE_IP, True) conf.pop(CONF_REQUIRE_IP, True)

View file

@ -58,8 +58,7 @@ class CoronavirusSensor(CoordinatorEntity, SensorEntity):
if self.country == OPTION_WORLDWIDE: if self.country == OPTION_WORLDWIDE:
sum_cases = 0 sum_cases = 0
for case in self.coordinator.data.values(): for case in self.coordinator.data.values():
value = getattr(case, self.info_type) if (value := getattr(case, self.info_type)) is None:
if value is None:
continue continue
sum_cases += value sum_cases += value

View file

@ -754,10 +754,9 @@ class DarkSkySensor(SensorEntity):
""" """
sensor_type = self.entity_description.key sensor_type = self.entity_description.key
lookup_type = convert_to_camel(sensor_type) lookup_type = convert_to_camel(sensor_type)
state = getattr(data, lookup_type, None)
if state is None: if (state := getattr(data, lookup_type, None)) is None:
return state return None
if "summary" in sensor_type: if "summary" in sensor_type:
self._icon = getattr(data, "icon", "") self._icon = getattr(data, "icon", "")

View file

@ -197,8 +197,7 @@ class SensorManager:
): ):
return return
current_entity = to_remove.pop(key, None) if current_entity := to_remove.pop(key, None):
if current_entity:
current_entity.update_config(config) current_entity.update_config(config)
return return

View file

@ -456,8 +456,7 @@ async def _setup_services(
for service in services: for service in services:
if service.key in old_services: if service.key in old_services:
# Already exists # Already exists
matching = old_services.pop(service.key) if (matching := old_services.pop(service.key)) != service:
if matching != service:
# Need to re-register # Need to re-register
to_unregister.append(matching) to_unregister.append(matching)
to_register.append(service) to_register.append(service)

View file

@ -84,8 +84,7 @@ async def async_attach_trigger(hass, config, action, automation_info):
def update_entity_trigger(entity_id, new_state=None): def update_entity_trigger(entity_id, new_state=None):
"""Update the entity trigger for the entity_id.""" """Update the entity trigger for the entity_id."""
# If a listener was already set up for entity, remove it. # If a listener was already set up for entity, remove it.
remove = entities.pop(entity_id, None) if remove := entities.pop(entity_id, None):
if remove:
remove() remove()
remove = None remove = None

View file

@ -659,8 +659,7 @@ class HomeKit:
async def async_remove_bridge_accessory(self, aid): async def async_remove_bridge_accessory(self, aid):
"""Try adding accessory to bridge if configured beforehand.""" """Try adding accessory to bridge if configured beforehand."""
acc = self.bridge.accessories.pop(aid, None) if acc := self.bridge.accessories.pop(aid, None):
if acc:
await acc.stop() await acc.stop()
return acc return acc

View file

@ -471,8 +471,7 @@ class HomekitControllerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
# available. Otherwise request a fresh copy from the API. # available. Otherwise request a fresh copy from the API.
# This removes the 'accessories' key from pairing_data at # This removes the 'accessories' key from pairing_data at
# the same time. # the same time.
accessories = pairing_data.pop("accessories", None) if not (accessories := pairing_data.pop("accessories", None)):
if not accessories:
accessories = await pairing.list_accessories_and_characteristics() accessories = await pairing.list_accessories_and_characteristics()
bridge_info = get_bridge_information(accessories) bridge_info = get_bridge_information(accessories)

View file

@ -218,8 +218,7 @@ class HomematicipBaseActionSensor(HomematicipGenericEntity, BinarySensorEntity):
state_attr = super().extra_state_attributes state_attr = super().extra_state_attributes
for attr, attr_key in SAM_DEVICE_ATTRIBUTES.items(): for attr, attr_key in SAM_DEVICE_ATTRIBUTES.items():
attr_value = getattr(self._device, attr, None) if attr_value := getattr(self._device, attr, None):
if attr_value:
state_attr[attr_key] = attr_value state_attr[attr_key] = attr_value
return state_attr return state_attr
@ -490,8 +489,7 @@ class HomematicipSecurityZoneSensorGroup(HomematicipGenericEntity, BinarySensorE
state_attr = super().extra_state_attributes state_attr = super().extra_state_attributes
for attr, attr_key in GROUP_ATTRIBUTES.items(): for attr, attr_key in GROUP_ATTRIBUTES.items():
attr_value = getattr(self._device, attr, None) if attr_value := getattr(self._device, attr, None):
if attr_value:
state_attr[attr_key] = attr_value state_attr[attr_key] = attr_value
window_state = getattr(self._device, "windowState", None) window_state = getattr(self._device, "windowState", None)

View file

@ -238,16 +238,14 @@ class HomematicipGenericEntity(Entity):
if isinstance(self._device, AsyncDevice): if isinstance(self._device, AsyncDevice):
for attr, attr_key in DEVICE_ATTRIBUTES.items(): for attr, attr_key in DEVICE_ATTRIBUTES.items():
attr_value = getattr(self._device, attr, None) if attr_value := getattr(self._device, attr, None):
if attr_value:
state_attr[attr_key] = attr_value state_attr[attr_key] = attr_value
state_attr[ATTR_IS_GROUP] = False state_attr[ATTR_IS_GROUP] = False
if isinstance(self._device, AsyncGroup): if isinstance(self._device, AsyncGroup):
for attr, attr_key in GROUP_ATTRIBUTES.items(): for attr, attr_key in GROUP_ATTRIBUTES.items():
attr_value = getattr(self._device, attr, None) if attr_value := getattr(self._device, attr, None):
if attr_value:
state_attr[attr_key] = attr_value state_attr[attr_key] = attr_value
state_attr[ATTR_IS_GROUP] = True state_attr[ATTR_IS_GROUP] = True

View file

@ -282,8 +282,7 @@ class HomematicipIlluminanceSensor(HomematicipGenericEntity, SensorEntity):
state_attr = super().extra_state_attributes state_attr = super().extra_state_attributes
for attr, attr_key in ILLUMINATION_DEVICE_ATTRIBUTES.items(): for attr, attr_key in ILLUMINATION_DEVICE_ATTRIBUTES.items():
attr_value = getattr(self._device, attr, None) if attr_value := getattr(self._device, attr, None):
if attr_value:
state_attr[attr_key] = attr_value state_attr[attr_key] = attr_value
return state_attr return state_attr

View file

@ -86,9 +86,7 @@ class HomeAssistantView:
routes: list[AbstractRoute] = [] routes: list[AbstractRoute] = []
for method in ("get", "post", "delete", "put", "patch", "head", "options"): for method in ("get", "post", "delete", "put", "patch", "head", "options"):
handler = getattr(self, method, None) if not (handler := getattr(self, method, None)):
if not handler:
continue continue
handler = request_handler_factory(self, handler) handler = request_handler_factory(self, handler)

View file

@ -252,16 +252,14 @@ def preprocess_turn_on_alternatives(hass, params):
if ATTR_PROFILE in params: if ATTR_PROFILE in params:
hass.data[DATA_PROFILES].apply_profile(params.pop(ATTR_PROFILE), params) hass.data[DATA_PROFILES].apply_profile(params.pop(ATTR_PROFILE), params)
color_name = params.pop(ATTR_COLOR_NAME, None) if (color_name := params.pop(ATTR_COLOR_NAME, None)) is not None:
if color_name is not None:
try: try:
params[ATTR_RGB_COLOR] = color_util.color_name_to_rgb(color_name) params[ATTR_RGB_COLOR] = color_util.color_name_to_rgb(color_name)
except ValueError: except ValueError:
_LOGGER.warning("Got unknown color %s, falling back to white", color_name) _LOGGER.warning("Got unknown color %s, falling back to white", color_name)
params[ATTR_RGB_COLOR] = (255, 255, 255) params[ATTR_RGB_COLOR] = (255, 255, 255)
kelvin = params.pop(ATTR_KELVIN, None) if (kelvin := params.pop(ATTR_KELVIN, None)) is not None:
if kelvin is not None:
mired = color_util.color_temperature_kelvin_to_mired(kelvin) mired = color_util.color_temperature_kelvin_to_mired(kelvin)
params[ATTR_COLOR_TEMP] = int(mired) params[ATTR_COLOR_TEMP] = int(mired)

View file

@ -162,8 +162,7 @@ class LockEntity(Entity):
"""Return the state attributes.""" """Return the state attributes."""
state_attr = {} state_attr = {}
for prop, attr in PROP_TO_ATTR.items(): for prop, attr in PROP_TO_ATTR.items():
value = getattr(self, prop) if (value := getattr(self, prop)) is not None:
if value is not None:
state_attr[attr] = value state_attr[attr] = value
return state_attr return state_attr

View file

@ -905,8 +905,7 @@ class MediaPlayerEntity(Entity):
return state_attr return state_attr
for attr in ATTR_TO_PROPERTY: for attr in ATTR_TO_PROPERTY:
value = getattr(self, attr) if (value := getattr(self, attr)) is not None:
if value is not None:
state_attr[attr] = value state_attr[attr] = value
if self.media_image_remotely_accessible: if self.media_image_remotely_accessible:

View file

@ -44,8 +44,7 @@ def log_messages(
def add_subscription(hass, message_callback, subscription): def add_subscription(hass, message_callback, subscription):
"""Prepare debug data for subscription.""" """Prepare debug data for subscription."""
entity_id = getattr(message_callback, "__entity_id", None) if entity_id := getattr(message_callback, "__entity_id", None):
if entity_id:
debug_info = hass.data.setdefault( debug_info = hass.data.setdefault(
DATA_MQTT_DEBUG_INFO, {"entities": {}, "triggers": {}} DATA_MQTT_DEBUG_INFO, {"entities": {}, "triggers": {}}
) )

View file

@ -210,8 +210,7 @@ class NestTempSensor(NestSensorDevice, SensorEntity):
else: else:
self._unit = TEMP_FAHRENHEIT self._unit = TEMP_FAHRENHEIT
temp = getattr(self.device, self.variable) if (temp := getattr(self.device, self.variable)) is None:
if temp is None:
self._state = None self._state = None
if isinstance(temp, tuple): if isinstance(temp, tuple):

View file

@ -238,8 +238,7 @@ class Plant(Entity):
result = [] result = []
for sensor_name in self._sensormap.values(): for sensor_name in self._sensormap.values():
params = self.READINGS[sensor_name] params = self.READINGS[sensor_name]
value = getattr(self, f"_{sensor_name}") if (value := getattr(self, f"_{sensor_name}")) is not None:
if value is not None:
if value == STATE_UNAVAILABLE: if value == STATE_UNAVAILABLE:
result.append(f"{sensor_name} unavailable") result.append(f"{sensor_name} unavailable")
else: else:

View file

@ -481,9 +481,7 @@ class PlexMediaPlayer(MediaPlayerEntity):
if isinstance(src, int): if isinstance(src, int):
src = {"plex_key": src} src = {"plex_key": src}
playqueue_id = src.pop("playqueue_id", None) if playqueue_id := src.pop("playqueue_id", None):
if playqueue_id:
try: try:
playqueue = self.plex_server.get_playqueue(playqueue_id) playqueue = self.plex_server.get_playqueue(playqueue_id)
except plexapi.exceptions.NotFound as err: except plexapi.exceptions.NotFound as err:
@ -518,8 +516,7 @@ class PlexMediaPlayer(MediaPlayerEntity):
"media_summary", "media_summary",
"username", "username",
): ):
value = getattr(self, attr, None) if value := getattr(self, attr, None):
if value:
attributes[attr] = value attributes[attr] = value
return attributes return attributes

View file

@ -107,8 +107,7 @@ def lookup_plex_media(hass, content_type, content_id):
plex_server_name = content.pop("plex_server", None) plex_server_name = content.pop("plex_server", None)
plex_server = get_plex_server(hass, plex_server_name) plex_server = get_plex_server(hass, plex_server_name)
playqueue_id = content.pop("playqueue_id", None) if playqueue_id := content.pop("playqueue_id", None):
if playqueue_id:
try: try:
playqueue = plex_server.get_playqueue(playqueue_id) playqueue = plex_server.get_playqueue(playqueue_id)
except NotFound as err: except NotFound as err:

View file

@ -262,8 +262,7 @@ class PrinterAPI:
printer = self.printers[printer_id] printer = self.printers[printer_id]
methods = API_PRINTER_METHODS[sensor_type] methods = API_PRINTER_METHODS[sensor_type]
for prop, offline in methods.offline.items(): for prop, offline in methods.offline.items():
state = getattr(printer, prop) if getattr(printer, prop) == offline:
if state == offline:
# if state matches offline, sensor is offline # if state matches offline, sensor is offline
return None return None

View file

@ -433,9 +433,7 @@ class ShellyBlockAttributeEntity(ShellyBlockEntity, entity.Entity):
@property @property
def attribute_value(self) -> StateType: def attribute_value(self) -> StateType:
"""Value of sensor.""" """Value of sensor."""
value = getattr(self.block, self.attribute) if (value := getattr(self.block, self.attribute)) is None:
if value is None:
return None return None
return cast(StateType, self.description.value(value)) return cast(StateType, self.description.value(value))

View file

@ -663,8 +663,7 @@ class SonosMediaPlayerEntity(SonosEntity, MediaPlayerEntity):
media_content_id, media_content_id,
MEDIA_TYPES_TO_SONOS[media_content_type], MEDIA_TYPES_TO_SONOS[media_content_type],
) )
image_url = getattr(item, "album_art_uri", None) if image_url := getattr(item, "album_art_uri", None):
if image_url:
result = await self._async_fetch_image(image_url) # type: ignore[no-untyped-call] result = await self._async_fetch_image(image_url) # type: ignore[no-untyped-call]
return result # type: ignore return result # type: ignore

View file

@ -114,8 +114,7 @@ class SwitchEntity(ToggleEntity):
data = {} data = {}
for prop, attr in PROP_TO_ATTR.items(): for prop, attr in PROP_TO_ATTR.items():
value = getattr(self, prop) if (value := getattr(self, prop)) is not None:
if value is not None:
data[attr] = value data[attr] = value
return data return data

View file

@ -100,8 +100,7 @@ def async_emeter_from_device(
) -> float | None: ) -> float | None:
"""Map a sensor key to the device attribute.""" """Map a sensor key to the device attribute."""
if attr := description.emeter_attr: if attr := description.emeter_attr:
val = getattr(device.emeter_realtime, attr) if (val := getattr(device.emeter_realtime, attr)) is None:
if val is None:
return None return None
return round(cast(float, val), description.precision) return round(cast(float, val), description.precision)

View file

@ -74,15 +74,13 @@ class WirelessTagPlatform:
def arm(self, switch): def arm(self, switch):
"""Arm entity sensor monitoring.""" """Arm entity sensor monitoring."""
func_name = f"arm_{switch.sensor_type}" func_name = f"arm_{switch.sensor_type}"
arm_func = getattr(self.api, func_name) if (arm_func := getattr(self.api, func_name)) is not None:
if arm_func is not None:
arm_func(switch.tag_id, switch.tag_manager_mac) arm_func(switch.tag_id, switch.tag_manager_mac)
def disarm(self, switch): def disarm(self, switch):
"""Disarm entity sensor monitoring.""" """Disarm entity sensor monitoring."""
func_name = f"disarm_{switch.sensor_type}" func_name = f"disarm_{switch.sensor_type}"
disarm_func = getattr(self.api, func_name) if (disarm_func := getattr(self.api, func_name)) is not None:
if disarm_func is not None:
disarm_func(switch.tag_id, switch.tag_manager_mac) disarm_func(switch.tag_id, switch.tag_manager_mac)
def start_monitoring(self): def start_monitoring(self):

View file

@ -117,8 +117,7 @@ class AirMonitorB1(XiaomiMiioEntity, AirQualityEntity):
data = {} data = {}
for prop, attr in PROP_TO_ATTR.items(): for prop, attr in PROP_TO_ATTR.items():
value = getattr(self, prop) if (value := getattr(self, prop)) is not None:
if value is not None:
data[attr] = value data[attr] = value
return data return data

View file

@ -293,8 +293,7 @@ class FlowManager(abc.ABC):
@callback @callback
def _async_remove_flow_progress(self, flow_id: str) -> None: def _async_remove_flow_progress(self, flow_id: str) -> None:
"""Remove a flow from in progress.""" """Remove a flow from in progress."""
flow = self._progress.pop(flow_id, None) if (flow := self._progress.pop(flow_id, None)) is None:
if flow is None:
raise UnknownFlow raise UnknownFlow
handler = flow.handler handler = flow.handler
self._handler_progress_index[handler].remove(flow.flow_id) self._handler_progress_index[handler].remove(flow.flow_id)

View file

@ -173,9 +173,7 @@ class EntityComponent:
"""Unload a config entry.""" """Unload a config entry."""
key = config_entry.entry_id key = config_entry.entry_id
platform = self._platforms.pop(key, None) if (platform := self._platforms.pop(key, None)) is None:
if platform is None:
raise ValueError("Config entry was never loaded!") raise ValueError("Config entry was never loaded!")
await platform.async_reset() await platform.async_reset()