Use assignment expressions 14 (#57939)

This commit is contained in:
Marc Mueller 2021-10-21 08:26:01 +02:00 committed by GitHub
parent 4eea618cc4
commit c979e89b70
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 31 additions and 70 deletions

View file

@ -88,9 +88,7 @@ class DdWrtDeviceScanner(DeviceScanner):
if not data: if not data:
return None return None
dhcp_leases = data.get("dhcp_leases") if not (dhcp_leases := data.get("dhcp_leases")):
if not dhcp_leases:
return None return None
# Remove leading and trailing quotes and spaces # Remove leading and trailing quotes and spaces

View file

@ -111,8 +111,7 @@ class DenonAvrFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
errors = {} errors = {}
if user_input is not None: if user_input is not None:
# check if IP address is set manually # check if IP address is set manually
host = user_input.get(CONF_HOST) if host := user_input.get(CONF_HOST):
if host:
self.host = host self.host = host
return await self.async_step_connect() return await self.async_step_connect()

View file

@ -36,8 +36,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
def setup_platform(hass, config, add_entities, discovery_info=None): def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Digital Ocean droplet sensor.""" """Set up the Digital Ocean droplet sensor."""
digital = hass.data.get(DATA_DIGITAL_OCEAN) if not (digital := hass.data.get(DATA_DIGITAL_OCEAN)):
if not digital:
return False return False
droplets = config[CONF_DROPLETS] droplets = config[CONF_DROPLETS]

View file

@ -33,8 +33,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
def setup_platform(hass, config, add_entities, discovery_info=None): def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Digital Ocean droplet switch.""" """Set up the Digital Ocean droplet switch."""
digital = hass.data.get(DATA_DIGITAL_OCEAN) if not (digital := hass.data.get(DATA_DIGITAL_OCEAN)):
if not digital:
return False return False
droplets = config[CONF_DROPLETS] droplets = config[CONF_DROPLETS]

View file

@ -22,9 +22,7 @@ class DovadoSMSNotificationService(BaseNotificationService):
def send_message(self, message, **kwargs): def send_message(self, message, **kwargs):
"""Send SMS to the specified target phone number.""" """Send SMS to the specified target phone number."""
target = kwargs.get(ATTR_TARGET) if not (target := kwargs.get(ATTR_TARGET)):
if not target:
_LOGGER.error("One target is required") _LOGGER.error("One target is required")
return return

View file

@ -113,8 +113,7 @@ class EcoNetWaterHeater(EcoNetEntity, WaterHeaterEntity):
def set_temperature(self, **kwargs): def set_temperature(self, **kwargs):
"""Set new target temperature.""" """Set new target temperature."""
target_temp = kwargs.get(ATTR_TEMPERATURE) if (target_temp := kwargs.get(ATTR_TEMPERATURE)) is not None:
if target_temp is not None:
self.water_heater.set_set_point(target_temp) self.water_heater.set_set_point(target_temp)
else: else:
_LOGGER.error("A target temperature must be provided") _LOGGER.error("A target temperature must be provided")

View file

@ -157,8 +157,7 @@ async def async_setup(hass, config):
} }
) )
sensor_configs = monitor_config[CONF_TEMPERATURE_SENSORS] if sensor_configs := monitor_config[CONF_TEMPERATURE_SENSORS]:
if sensor_configs:
temperature_unit = { temperature_unit = {
CONF_TEMPERATURE_UNIT: sensor_configs[CONF_TEMPERATURE_UNIT] CONF_TEMPERATURE_UNIT: sensor_configs[CONF_TEMPERATURE_UNIT]
} }

View file

@ -213,8 +213,7 @@ class HabitipyTaskSensor(SensorEntity):
task_id = received_task[TASKS_MAP_ID] task_id = received_task[TASKS_MAP_ID]
task = {} task = {}
for map_key, map_value in TASKS_MAP.items(): for map_key, map_value in TASKS_MAP.items():
value = received_task.get(map_value) if value := received_task.get(map_value):
if value:
task[map_key] = value task[map_key] = value
attrs[task_id] = task attrs[task_id] = task
return attrs return attrs

View file

@ -88,9 +88,7 @@ CONFIG_SCHEMA = vol.Schema(
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up iCloud from legacy config file.""" """Set up iCloud from legacy config file."""
if (conf := config.get(DOMAIN)) is None:
conf = config.get(DOMAIN)
if conf is None:
return True return True
for account_conf in conf: for account_conf in conf:
@ -169,9 +167,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
def update_account(service: ServiceDataType) -> None: def update_account(service: ServiceDataType) -> None:
"""Call the update function of an iCloud account.""" """Call the update function of an iCloud account."""
account = service.data.get(ATTR_ACCOUNT) if (account := service.data.get(ATTR_ACCOUNT)) is None:
if account is None:
for account in hass.data[DOMAIN].values(): for account in hass.data[DOMAIN].values():
account.keep_alive() account.keep_alive()
else: else:

View file

@ -259,13 +259,10 @@ class IntesisAC(ClimateEntity):
async def async_set_temperature(self, **kwargs): async def async_set_temperature(self, **kwargs):
"""Set new target temperature.""" """Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE) if hvac_mode := kwargs.get(ATTR_HVAC_MODE):
hvac_mode = kwargs.get(ATTR_HVAC_MODE)
if hvac_mode:
await self.async_set_hvac_mode(hvac_mode) await self.async_set_hvac_mode(hvac_mode)
if temperature: if temperature := kwargs.get(ATTR_TEMPERATURE):
_LOGGER.debug("Setting %s to %s degrees", self._device_type, temperature) _LOGGER.debug("Setting %s to %s degrees", self._device_type, temperature)
await self._controller.set_temperature(self._device_id, temperature) await self._controller.set_temperature(self._device_id, temperature)
self._target_temp = temperature self._target_temp = temperature

View file

@ -176,8 +176,7 @@ class LcnClimate(LcnEntity, ClimateEntity):
async def async_set_temperature(self, **kwargs: Any) -> None: async def async_set_temperature(self, **kwargs: Any) -> 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
if not await self.device_connection.var_abs( if not await self.device_connection.var_abs(

View file

@ -208,8 +208,7 @@ def has_unique_host_names(hosts: list[ConfigType]) -> list[ConfigType]:
""" """
suffix = 0 suffix = 0
for host in hosts: for host in hosts:
host_name = host.get(CONF_NAME) if host.get(CONF_NAME) is None:
if host_name is None:
if suffix == 0: if suffix == 0:
host[CONF_NAME] = DEFAULT_NAME host[CONF_NAME] = DEFAULT_NAME
else: else:

View file

@ -307,8 +307,7 @@ class SendKeys(LcnServiceCall):
key_id = int(key) - 1 key_id = int(key) - 1
keys[table_id][key_id] = True keys[table_id][key_id] = True
delay_time = service.data[CONF_TIME] if (delay_time := service.data[CONF_TIME]) != 0:
if delay_time != 0:
hit = pypck.lcn_defs.SendKeyCommand.HIT hit = pypck.lcn_defs.SendKeyCommand.HIT
if pypck.lcn_defs.SendKeyCommand[service.data[CONF_STATE]] != hit: if pypck.lcn_defs.SendKeyCommand[service.data[CONF_STATE]] != hit:
raise ValueError( raise ValueError(
@ -347,8 +346,7 @@ class LockKeys(LcnServiceCall):
] ]
table_id = ord(service.data[CONF_TABLE]) - 65 table_id = ord(service.data[CONF_TABLE]) - 65
delay_time = service.data[CONF_TIME] if (delay_time := service.data[CONF_TIME]) != 0:
if delay_time != 0:
if table_id != 0: if table_id != 0:
raise ValueError( raise ValueError(
"Only table A is allowed when locking keys for a specific time." "Only table A is allowed when locking keys for a specific time."

View file

@ -32,9 +32,7 @@ async def _async_reproduce_state(
reproduce_options: dict[str, Any] | None = None, reproduce_options: dict[str, Any] | None = None,
) -> None: ) -> None:
"""Reproduce a single state.""" """Reproduce a single state."""
cur_state = hass.states.get(state.entity_id) if (cur_state := hass.states.get(state.entity_id)) is None:
if cur_state is None:
_LOGGER.warning("Unable to find entity %s", state.entity_id) _LOGGER.warning("Unable to find entity %s", state.entity_id)
return return

View file

@ -56,7 +56,6 @@ class OPNSenseDeviceScanner(DeviceScanner):
"""Return the extra attrs of the given device.""" """Return the extra attrs of the given device."""
if device not in self.last_results: if device not in self.last_results:
return None return None
mfg = self.last_results[device].get("manufacturer") if not (mfg := self.last_results[device].get("manufacturer")):
if not mfg:
return {} return {}
return {"manufacturer": mfg} return {"manufacturer": mfg}

View file

@ -242,9 +242,7 @@ class OwnTracksContext:
@callback @callback
def async_valid_accuracy(self, message): def async_valid_accuracy(self, message):
"""Check if we should ignore this message.""" """Check if we should ignore this message."""
acc = message.get("acc") if (acc := message.get("acc")) is None:
if acc is None:
return False return False
try: try:

View file

@ -73,8 +73,7 @@ async def async_setup_entry(hass, config_entry):
host = config[CONF_HOST] host = config[CONF_HOST]
port = config[CONF_PORT] port = config[CONF_PORT]
on_action = config[CONF_ON_ACTION] if (on_action := config[CONF_ON_ACTION]) is not None:
if on_action is not None:
on_action = Script(hass, on_action, config[CONF_NAME], DOMAIN) on_action = Script(hass, on_action, config[CONF_NAME], DOMAIN)
params = {} params = {}

View file

@ -164,8 +164,7 @@ class RiscoAlarm(AlarmControlPanelEntity, RiscoEntity):
_LOGGER.warning("Wrong code entered for %s", mode) _LOGGER.warning("Wrong code entered for %s", mode)
return return
risco_state = self._ha_to_risco[mode] if not (risco_state := self._ha_to_risco[mode]):
if not risco_state:
_LOGGER.warning("No mapping for mode %s", mode) _LOGGER.warning("No mapping for mode %s", mode)
return return

View file

@ -97,8 +97,7 @@ async def build_item_response(entity, player, payload):
item_id = str(item["id"]) item_id = str(item["id"])
item_thumbnail = None item_thumbnail = None
artwork_track_id = item.get("artwork_track_id") if artwork_track_id := item.get("artwork_track_id"):
if artwork_track_id:
if internal_request: if internal_request:
item_thumbnail = player.generate_image_url_from_track_id( item_thumbnail = player.generate_image_url_from_track_id(
artwork_track_id artwork_track_id

View file

@ -561,8 +561,7 @@ class SqueezeBoxEntity(MediaPlayerEntity):
player_ids = { player_ids = {
p.entity_id: p.unique_id for p in self.hass.data[DOMAIN][KNOWN_PLAYERS] p.entity_id: p.unique_id for p in self.hass.data[DOMAIN][KNOWN_PLAYERS]
} }
other_player_id = player_ids.get(other_player) if other_player_id := player_ids.get(other_player):
if other_player_id:
await self._player.async_sync(other_player_id) await self._player.async_sync(other_player_id)
else: else:
_LOGGER.info("Could not find player_id for %s. Not syncing", other_player) _LOGGER.info("Could not find player_id for %s. Not syncing", other_player)

View file

@ -329,8 +329,7 @@ async def async_setup(hass, config):
"""Handle sending Telegram Bot message service calls.""" """Handle sending Telegram Bot message service calls."""
def _render_template_attr(data, attribute): def _render_template_attr(data, attribute):
attribute_templ = data.get(attribute) if attribute_templ := data.get(attribute):
if attribute_templ:
if any( if any(
isinstance(attribute_templ, vtype) for vtype in (float, int, str) isinstance(attribute_templ, vtype) for vtype in (float, int, str)
): ):

View file

@ -76,8 +76,7 @@ def setup(hass, config):
kwargs = {"mid": ring_id} kwargs = {"mid": ring_id}
ring_vol = call.data.get(ATTR_RINGTONE_VOL) if (ring_vol := call.data.get(ATTR_RINGTONE_VOL)) is not None:
if ring_vol is not None:
kwargs["vol"] = ring_vol kwargs["vol"] = ring_vol
gateway.write_to_hub(gateway.sid, **kwargs) gateway.write_to_hub(gateway.sid, **kwargs)
@ -379,8 +378,7 @@ def _add_gateway_to_schema(hass, schema):
raise vol.Invalid(f"Unknown gateway sid {sid}") raise vol.Invalid(f"Unknown gateway sid {sid}")
kwargs = {} kwargs = {}
xiaomi_data = hass.data.get(DOMAIN) if (xiaomi_data := hass.data.get(DOMAIN)) is not None:
if xiaomi_data is not None:
gateways = list(xiaomi_data[GATEWAYS_KEY].values()) gateways = list(xiaomi_data[GATEWAYS_KEY].values())
# If the user has only 1 gateway, make it the default for services. # If the user has only 1 gateway, make it the default for services.

View file

@ -76,10 +76,8 @@ class XiaomiAqaraFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
if self.host is None: if self.host is None:
self.host = user_input.get(CONF_HOST) self.host = user_input.get(CONF_HOST)
if self.sid is None: if self.sid is None:
mac_address = user_input.get(CONF_MAC)
# format sid from mac_address # format sid from mac_address
if mac_address is not None: if (mac_address := user_input.get(CONF_MAC)) is not None:
self.sid = format_mac(mac_address).replace(":", "") self.sid = format_mac(mac_address).replace(":", "")
# if host is already known by zeroconf discovery or manual optional settings # if host is already known by zeroconf discovery or manual optional settings

View file

@ -22,8 +22,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities = [] entities = []
gateway = hass.data[DOMAIN][GATEWAYS_KEY][config_entry.entry_id] gateway = hass.data[DOMAIN][GATEWAYS_KEY][config_entry.entry_id]
for device in gateway.devices["lock"]: for device in gateway.devices["lock"]:
model = device["model"] if device["model"] == "lock.aq1":
if model == "lock.aq1":
entities.append(XiaomiAqaraLock(device, "Lock", gateway, config_entry)) entities.append(XiaomiAqaraLock(device, "Lock", gateway, config_entry))
async_add_entities(entities) async_add_entities(entities)
@ -63,14 +62,12 @@ class XiaomiAqaraLock(LockEntity, XiaomiDevice):
def parse_data(self, data, raw_data): def parse_data(self, data, raw_data):
"""Parse data sent by gateway.""" """Parse data sent by gateway."""
value = data.get(VERIFIED_WRONG_KEY) if (value := data.get(VERIFIED_WRONG_KEY)) is not None:
if value is not None:
self._verified_wrong_times = int(value) self._verified_wrong_times = int(value)
return True return True
for key in (FINGER_KEY, PASSWORD_KEY, CARD_KEY): for key in (FINGER_KEY, PASSWORD_KEY, CARD_KEY):
value = data.get(key) if (value := data.get(key)) is not None:
if value is not None:
self._changed_by = int(value) self._changed_by = int(value)
self._verified_wrong_times = 0 self._verified_wrong_times = 0
self._state = STATE_UNLOCKED self._state = STATE_UNLOCKED

View file

@ -158,8 +158,7 @@ class XiaomiSensor(XiaomiDevice, SensorEntity):
def parse_data(self, data, raw_data): def parse_data(self, data, raw_data):
"""Parse data sent by gateway.""" """Parse data sent by gateway."""
value = data.get(self._data_key) if (value := data.get(self._data_key)) is None:
if value is None:
return False return False
if self._data_key in ("coordination", "status"): if self._data_key in ("coordination", "status"):
self._attr_native_value = value self._attr_native_value = value