Use assignment expressions 21 (#57970)

This commit is contained in:
Marc Mueller 2021-10-20 17:47:46 +02:00 committed by GitHub
parent d20936d175
commit ea7252e377
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 28 additions and 56 deletions

View File

@ -91,8 +91,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
mode = config.get(CONF_MODE) mode = config.get(CONF_MODE)
units = config.get(CONF_UNITS) if not (units := config.get(CONF_UNITS)):
if not units:
units = "ca" if hass.config.units.is_metric else "us" units = "ca" if hass.config.units.is_metric else "us"
dark_sky = DarkSkyData(config.get(CONF_API_KEY), latitude, longitude, units) dark_sky = DarkSkyData(config.get(CONF_API_KEY), latitude, longitude, units)

View File

@ -178,8 +178,7 @@ class EDL21:
new_entities = [] new_entities = []
for telegram in message_body.get("valList", []): for telegram in message_body.get("valList", []):
obis = telegram.get("objName") if not (obis := telegram.get("objName")):
if not obis:
continue continue
if (electricity_id, obis) in self._registered_obis: if (electricity_id, obis) in self._registered_obis:
@ -187,8 +186,7 @@ class EDL21:
self._hass, SIGNAL_EDL21_TELEGRAM, electricity_id, telegram self._hass, SIGNAL_EDL21_TELEGRAM, electricity_id, telegram
) )
else: else:
name = self._OBIS_NAMES.get(obis) if name := self._OBIS_NAMES.get(obis):
if name:
if self._name: if self._name:
name = f"{self._name}: {name}" name = f"{self._name}: {name}"
new_entities.append( new_entities.append(

View File

@ -399,8 +399,7 @@ def _async_register_events_and_services(hass: HomeAssistant):
referenced = async_extract_referenced_entity_ids(hass, service) referenced = async_extract_referenced_entity_ids(hass, service)
dev_reg = device_registry.async_get(hass) dev_reg = device_registry.async_get(hass)
for device_id in referenced.referenced_devices: for device_id in referenced.referenced_devices:
dev_reg_ent = dev_reg.async_get(device_id) if not (dev_reg_ent := dev_reg.async_get(device_id)):
if not dev_reg_ent:
raise HomeAssistantError(f"No device found for device id: {device_id}") raise HomeAssistantError(f"No device found for device id: {device_id}")
macs = [ macs = [
cval cval
@ -697,8 +696,7 @@ class HomeKit:
if not self._filter(entity_id): if not self._filter(entity_id):
continue continue
ent_reg_ent = ent_reg.async_get(entity_id) if ent_reg_ent := ent_reg.async_get(entity_id):
if ent_reg_ent:
await self._async_set_device_info_attributes( await self._async_set_device_info_attributes(
ent_reg_ent, dev_reg, entity_id ent_reg_ent, dev_reg, entity_id
) )

View File

@ -413,8 +413,7 @@ class HomeAccessory(Accessory):
@ha_callback @ha_callback
def async_update_linked_battery_callback(self, event): def async_update_linked_battery_callback(self, event):
"""Handle linked battery sensor state change listener callback.""" """Handle linked battery sensor state change listener callback."""
new_state = event.data.get("new_state") if (new_state := event.data.get("new_state")) is None:
if new_state is None:
return return
if self.linked_battery_charging_sensor: if self.linked_battery_charging_sensor:
battery_charging_state = None battery_charging_state = None
@ -425,8 +424,7 @@ class HomeAccessory(Accessory):
@ha_callback @ha_callback
def async_update_linked_battery_charging_callback(self, event): def async_update_linked_battery_charging_callback(self, event):
"""Handle linked battery charging sensor state change listener callback.""" """Handle linked battery charging sensor state change listener callback."""
new_state = event.data.get("new_state") if (new_state := event.data.get("new_state")) is None:
if new_state is None:
return return
self.async_update_battery(None, new_state.state == STATE_ON) self.async_update_battery(None, new_state.state == STATE_ON)
@ -524,8 +522,7 @@ class HomeBridge(Bridge):
async def async_get_snapshot(self, info): async def async_get_snapshot(self, info):
"""Get snapshot from accessory if supported.""" """Get snapshot from accessory if supported."""
acc = self.accessories.get(info["aid"]) if (acc := self.accessories.get(info["aid"])) is None:
if acc is None:
raise ValueError("Requested snapshot for missing accessory") raise ValueError("Requested snapshot for missing accessory")
if not hasattr(acc, "async_get_snapshot"): if not hasattr(acc, "async_get_snapshot"):
raise ValueError( raise ValueError(

View File

@ -314,8 +314,7 @@ class Camera(HomeAccessory, PyhapCamera):
async def _async_get_stream_source(self): async def _async_get_stream_source(self):
"""Find the camera stream source url.""" """Find the camera stream source url."""
stream_source = self.config.get(CONF_STREAM_SOURCE) if stream_source := self.config.get(CONF_STREAM_SOURCE):
if stream_source:
return stream_source return stream_source
try: try:
stream_source = await self.hass.components.camera.async_get_stream_source( stream_source = await self.hass.components.camera.async_get_stream_source(
@ -447,8 +446,7 @@ class Camera(HomeAccessory, PyhapCamera):
async def stop_stream(self, session_info): async def stop_stream(self, session_info):
"""Stop the stream for the given ``session_id``.""" """Stop the stream for the given ``session_id``."""
session_id = session_info["id"] session_id = session_info["id"]
stream = session_info.get("stream") if not (stream := session_info.get("stream")):
if not stream:
_LOGGER.debug("No stream for session ID %s", session_id) _LOGGER.debug("No stream for session ID %s", session_id)
return return

View File

@ -303,8 +303,7 @@ class TelevisionMediaPlayer(RemoteInputSelectAccessory):
def set_remote_key(self, value): def set_remote_key(self, value):
"""Send remote key value if call came from HomeKit.""" """Send remote key value if call came from HomeKit."""
_LOGGER.debug("%s: Set remote key to %s", self.entity_id, value) _LOGGER.debug("%s: Set remote key to %s", self.entity_id, value)
key_name = REMOTE_KEYS.get(value) if (key_name := REMOTE_KEYS.get(value)) is None:
if key_name is None:
_LOGGER.warning("%s: Unhandled key press for %s", self.entity_id, value) _LOGGER.warning("%s: Unhandled key press for %s", self.entity_id, value)
return return

View File

@ -207,8 +207,7 @@ class ActivityRemote(RemoteInputSelectAccessory):
def set_remote_key(self, value): def set_remote_key(self, value):
"""Send remote key value if call came from HomeKit.""" """Send remote key value if call came from HomeKit."""
_LOGGER.debug("%s: Set remote key to %s", self.entity_id, value) _LOGGER.debug("%s: Set remote key to %s", self.entity_id, value)
key_name = REMOTE_KEYS.get(value) if (key_name := REMOTE_KEYS.get(value)) is None:
if key_name is None:
_LOGGER.warning("%s: Unhandled key press for %s", self.entity_id, value) _LOGGER.warning("%s: Unhandled key press for %s", self.entity_id, value)
return return
self.hass.bus.async_fire( self.hass.bus.async_fire(

View File

@ -462,8 +462,7 @@ class Thermostat(HomeAccessory):
) )
# Set current operation mode for supported thermostats # Set current operation mode for supported thermostats
hvac_action = new_state.attributes.get(ATTR_HVAC_ACTION) if hvac_action := new_state.attributes.get(ATTR_HVAC_ACTION):
if hvac_action:
homekit_hvac_action = HC_HASS_TO_HOMEKIT_ACTION[hvac_action] homekit_hvac_action = HC_HASS_TO_HOMEKIT_ACTION[hvac_action]
self.char_current_heat_cool.set_value(homekit_hvac_action) self.char_current_heat_cool.set_value(homekit_hvac_action)
@ -575,8 +574,7 @@ class WaterHeater(HomeAccessory):
def set_heat_cool(self, value): def set_heat_cool(self, value):
"""Change operation mode to value if call came from HomeKit.""" """Change operation mode to value if call came from HomeKit."""
_LOGGER.debug("%s: Set heat-cool to %d", self.entity_id, value) _LOGGER.debug("%s: Set heat-cool to %d", self.entity_id, value)
hass_value = HC_HOMEKIT_TO_HASS[value] if HC_HOMEKIT_TO_HASS[value] != HVAC_MODE_HEAT:
if hass_value != HVAC_MODE_HEAT:
self.char_target_heat_cool.set_value(1) # Heat self.char_target_heat_cool.set_value(1) # Heat
def set_target_temperature(self, value): def set_target_temperature(self, value):
@ -615,14 +613,12 @@ class WaterHeater(HomeAccessory):
def _get_temperature_range_from_state(state, unit, default_min, default_max): def _get_temperature_range_from_state(state, unit, default_min, default_max):
"""Calculate the temperature range from a state.""" """Calculate the temperature range from a state."""
min_temp = state.attributes.get(ATTR_MIN_TEMP) if min_temp := state.attributes.get(ATTR_MIN_TEMP):
if min_temp:
min_temp = round(temperature_to_homekit(min_temp, unit) * 2) / 2 min_temp = round(temperature_to_homekit(min_temp, unit) * 2) / 2
else: else:
min_temp = default_min min_temp = default_min
max_temp = state.attributes.get(ATTR_MAX_TEMP) if max_temp := state.attributes.get(ATTR_MAX_TEMP):
if max_temp:
max_temp = round(temperature_to_homekit(max_temp, unit) * 2) / 2 max_temp = round(temperature_to_homekit(max_temp, unit) * 2) / 2
else: else:
max_temp = default_max max_temp = default_max

View File

@ -55,8 +55,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
config.get(CONF_FOLDER), config.get(CONF_FOLDER),
) )
value_template = config.get(CONF_VALUE_TEMPLATE) if (value_template := config.get(CONF_VALUE_TEMPLATE)) is not None:
if value_template is not None:
value_template.hass = hass value_template.hass = hass
sensor = EmailContentSensor( sensor = EmailContentSensor(
hass, hass,

View File

@ -450,8 +450,7 @@ class ManualMQTTAlarm(alarm.AlarmControlPanelEntity):
async def _async_state_changed_listener(self, event): async def _async_state_changed_listener(self, event):
"""Publish state change to MQTT.""" """Publish state change to MQTT."""
new_state = event.data.get("new_state") if (new_state := event.data.get("new_state")) is None:
if new_state is None:
return return
mqtt.async_publish( mqtt.async_publish(
self.hass, self._state_topic, new_state.state, self._qos, True self.hass, self._state_topic, new_state.state, self._qos, True

View File

@ -187,8 +187,7 @@ class PhilipsTVMediaPlayer(CoordinatorEntity, MediaPlayerEntity):
async def async_select_source(self, source): async def async_select_source(self, source):
"""Set the input source.""" """Set the input source."""
source_id = _inverted(self._sources).get(source) if source_id := _inverted(self._sources).get(source):
if source_id:
await self._tv.setSource(source_id) await self._tv.setSource(source_id)
await self._async_update_soon() await self._async_update_soon()
@ -316,8 +315,7 @@ class PhilipsTVMediaPlayer(CoordinatorEntity, MediaPlayerEntity):
@property @property
def app_name(self): def app_name(self):
"""Name of the current running app.""" """Name of the current running app."""
app = self._tv.applications.get(self._tv.application_id) if app := self._tv.applications.get(self._tv.application_id):
if app:
return app.get("label") return app.get("label")
@property @property
@ -350,8 +348,7 @@ class PhilipsTVMediaPlayer(CoordinatorEntity, MediaPlayerEntity):
else: else:
_LOGGER.error("Unable to find channel <%s>", media_id) _LOGGER.error("Unable to find channel <%s>", media_id)
elif media_type == MEDIA_TYPE_APP: elif media_type == MEDIA_TYPE_APP:
app = self._tv.applications.get(media_id) if app := self._tv.applications.get(media_id):
if app:
await self._tv.setApplication(app["intent"]) await self._tv.setApplication(app["intent"])
await self._async_update_soon() await self._async_update_soon()
else: else:

View File

@ -94,8 +94,7 @@ class SomfyClimate(SomfyEntity, ClimateEntity):
def set_temperature(self, **kwargs) -> None: def set_temperature(self, **kwargs) -> None:
"""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
self._climate.set_target(TargetMode.MANUAL, temperature, DurationType.NEXT_MODE) self._climate.set_target(TargetMode.MANUAL, temperature, DurationType.NEXT_MODE)

View File

@ -427,8 +427,7 @@ class SpeechManager:
This method is a coroutine. This method is a coroutine.
""" """
filename = self.file_cache.get(key) if not (filename := self.file_cache.get(key)):
if not filename:
raise HomeAssistantError(f"Key {key} not in file cache!") raise HomeAssistantError(f"Key {key} not in file cache!")
voice_file = os.path.join(self.cache_dir, filename) voice_file = os.path.join(self.cache_dir, filename)

View File

@ -68,9 +68,7 @@ async def async_setup(hass: HomeAssistant, base_config: ConfigType) -> bool:
"""Set up for Vera controllers.""" """Set up for Vera controllers."""
hass.data[DOMAIN] = {} hass.data[DOMAIN] = {}
config = base_config.get(DOMAIN) if not (config := base_config.get(DOMAIN)):
if not config:
return True return True
hass.async_create_task( hass.async_create_task(

View File

@ -117,8 +117,7 @@ class WemoLight(WemoEntity, LightEntity):
@property @property
def hs_color(self): def hs_color(self):
"""Return the hs color values of this light.""" """Return the hs color values of this light."""
xy_color = self.light.state.get("color_xy") if xy_color := self.light.state.get("color_xy"):
if xy_color:
return color_util.color_xy_to_hs(*xy_color) return color_util.color_xy_to_hs(*xy_color)
return None return None

View File

@ -35,7 +35,7 @@ async def async_setup_entry(
"""Initialize the integration.""" """Initialize the integration."""
coordinator = hass.data[DOMAIN][entry.entry_id] coordinator = hass.data[DOMAIN][entry.entry_id]
device = entry.data[CONF_DEVICE] device = entry.data[CONF_DEVICE]
if device is None: if (device := entry.data[CONF_DEVICE]) is None:
device = entry.entry_id device = entry.entry_id
async_add_entities( async_add_entities(

View File

@ -239,12 +239,10 @@ class ZhongHongClimate(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 not None:
if temperature is not None:
self._device.set_temperature(temperature) self._device.set_temperature(temperature)
operation_mode = kwargs.get(ATTR_HVAC_MODE) if (operation_mode := kwargs.get(ATTR_HVAC_MODE)) is not None:
if operation_mode is not None:
self.set_hvac_mode(operation_mode) self.set_hvac_mode(operation_mode)
def set_hvac_mode(self, hvac_mode): def set_hvac_mode(self, hvac_mode):