1
mirror of https://github.com/home-assistant/core synced 2024-07-12 07:21:24 +02:00

Use assignment expressions 28 (#58189)

This commit is contained in:
Marc Mueller 2021-10-22 14:06:04 +02:00 committed by GitHub
parent a3d1159a13
commit eab235173b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 30 additions and 61 deletions

View File

@ -245,8 +245,7 @@ class NotifyAuthModule(MultiFactorAuthModule):
await self._async_load()
assert self._user_settings is not None
notify_setting = self._user_settings.get(user_id)
if notify_setting is None:
if (notify_setting := self._user_settings.get(user_id)) is None:
_LOGGER.error("Cannot find user %s", user_id)
return

View File

@ -396,8 +396,7 @@ async def get_tracker(hass: HomeAssistant, config: ConfigType) -> DeviceTracker:
consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME)
defaults = conf.get(CONF_NEW_DEVICE_DEFAULTS, {})
track_new = conf.get(CONF_TRACK_NEW)
if track_new is None:
if (track_new := conf.get(CONF_TRACK_NEW)) is None:
track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)
devices = await async_load_config(yaml_path, hass, consider_home)
@ -492,8 +491,7 @@ class DeviceTracker:
raise HomeAssistantError("Neither mac or device id passed in")
if mac is not None:
mac = str(mac).upper()
device = self.mac_to_dev.get(mac)
if device is None:
if (device := self.mac_to_dev.get(mac)) is None:
dev_id = util.slugify(host_name or "") or util.slugify(mac)
else:
dev_id = cv.slug(str(dev_id).lower())

View File

@ -106,8 +106,7 @@ async def async_handle_message(hass, message):
"Dialogflow V1 API will be removed on October 23, 2019. Please change your DialogFlow settings to use the V2 api"
)
req = message.get("result")
action_incomplete = req.get("actionIncomplete", True)
if action_incomplete:
if req.get("actionIncomplete", True):
return
elif _api_version is V2:

View File

@ -34,9 +34,8 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
file_path = config.get(CONF_FILE_PATH)
name = config.get(CONF_NAME)
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
if (value_template := config.get(CONF_VALUE_TEMPLATE)) is not None:
value_template.hass = hass
if hass.config.is_allowed_path(file_path):

View File

@ -123,8 +123,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
if not (entity_class := ENTITY_TYPES.get(service.short_type)):
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)

View File

@ -93,8 +93,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
if not (entity_class := ENTITY_TYPES.get(service.short_type)):
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)

View File

@ -41,8 +41,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
if not (entity_class := ENTITY_TYPES.get(service.short_type)):
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)

View File

@ -154,8 +154,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
if not (entity_class := ENTITY_TYPES.get(service.short_type)):
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)

View File

@ -362,8 +362,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
if not (entity_class := ENTITY_TYPES.get(service.short_type)):
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)

View File

@ -110,8 +110,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
@callback
def async_add_service(service):
entity_class = ENTITY_TYPES.get(service.short_type)
if not entity_class:
if not (entity_class := ENTITY_TYPES.get(service.short_type)):
return False
info = {"aid": service.accessory.aid, "iid": service.iid}
async_add_entities([entity_class(conn, info)], True)

View File

@ -205,8 +205,7 @@ class LogbookView(HomeAssistantView):
else:
period = int(period)
entity_ids = request.query.get("entity")
if entity_ids:
if entity_ids := request.query.get("entity"):
try:
entity_ids = cv.entity_ids(entity_ids)
except vol.Invalid:

View File

@ -200,8 +200,7 @@ class MaxCubeClimate(ClimateEntity):
def set_temperature(self, **kwargs):
"""Set new target temperatures."""
temp = kwargs.get(ATTR_TEMPERATURE)
if temp is None:
if (temp := kwargs.get(ATTR_TEMPERATURE)) is None:
raise ValueError(
f"No {ATTR_TEMPERATURE} parameter passed to set_temperature method."
)

View File

@ -43,8 +43,7 @@ CONFIG_SCHEMA = vol.Schema(
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up Meteo-France from legacy config file."""
conf = config.get(DOMAIN)
if not conf:
if not (conf := config.get(DOMAIN)):
return True
for city_conf in conf:

View File

@ -202,9 +202,8 @@ class BaseNotificationService:
"""Handle sending notification message service calls."""
kwargs = {}
message = service.data[ATTR_MESSAGE]
title = service.data.get(ATTR_TITLE)
if title:
if title := service.data.get(ATTR_TITLE):
check_templates_warn(self.hass, title)
title.hass = self.hass
kwargs[ATTR_TITLE] = title.async_render(parse_result=False)

View File

@ -254,9 +254,7 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
Must know if single or double setpoint.
"""
hvac_mode = kwargs.get(ATTR_HVAC_MODE)
if hvac_mode is not None:
if (hvac_mode := kwargs.get(ATTR_HVAC_MODE)) is not None:
await self.async_set_hvac_mode(hvac_mode)
if len(self._current_mode_setpoint_values) == 1:
@ -290,8 +288,7 @@ class ZWaveClimateEntity(ZWaveDeviceEntity, ClimateEntity):
"Thermostat %s does not support setting a mode", self.entity_id
)
return
hvac_mode_value = self._hvac_modes.get(hvac_mode)
if hvac_mode_value is None:
if (hvac_mode_value := self._hvac_modes.get(hvac_mode)) is None:
_LOGGER.warning("Received an invalid hvac mode: %s", hvac_mode)
return
self.values.mode.send_value(hvac_mode_value)

View File

@ -177,8 +177,7 @@ class ZwaveLight(ZWaveDeviceEntity, LightEntity):
# transition specified by user
new_value = int(max(0, min(7620, kwargs[ATTR_TRANSITION])))
if ozw_version < (1, 6, 1205):
transition = kwargs[ATTR_TRANSITION]
if transition <= 127:
if (transition := kwargs[ATTR_TRANSITION]) <= 127:
new_value = int(transition)
else:
minutes = int(transition / 60)

View File

@ -48,9 +48,7 @@ def async_check_significant_change(
**kwargs: Any,
) -> bool | None:
"""Test if state significantly changed."""
device_class = new_attrs.get(ATTR_DEVICE_CLASS)
if device_class is None:
if (device_class := new_attrs.get(ATTR_DEVICE_CLASS)) is None:
return None
absolute_change: float | None = None

View File

@ -132,8 +132,7 @@ class TankerkoenigData:
return False
# Add stations found via location + radius
nearby_stations = data["stations"]
if not nearby_stations:
if not (nearby_stations := data["stations"]):
if not additional_stations:
_LOGGER.error(
"Could not find any station in range."
@ -144,7 +143,7 @@ class TankerkoenigData:
"Could not find any station in range. Will only use manually specified stations"
)
else:
for station in data["stations"]:
for station in nearby_stations:
self.add_station(station)
# Add manually specified additional stations

View File

@ -143,8 +143,7 @@ class ValloxStateProxy:
if metric_key not in vlxDevConstants.__dict__:
raise KeyError(f"Unknown metric key: {metric_key}")
value = self._metric_cache[metric_key]
if value is None:
if (value := self._metric_cache[metric_key]) is None:
return None
if not isinstance(value, (str, int, float)):

View File

@ -140,8 +140,7 @@ async def async_setup_entry( # noqa: C901
hass: HomeAssistant, entry: ConfigEntry
) -> bool:
"""Set up Z-Wave JS from a config entry."""
use_addon = entry.data.get(CONF_USE_ADDON)
if use_addon:
if use_addon := entry.data.get(CONF_USE_ADDON):
await async_ensure_addon_running(hass, entry)
client = ZwaveClient(entry.data[CONF_URL], async_get_clientsession(hass))

View File

@ -209,8 +209,7 @@ class ZWaveClimate(ZWaveBaseEntity, ClimateEntity):
def _setpoint_value(self, setpoint_type: ThermostatSetpointType) -> ZwaveValue:
"""Optionally return a ZwaveValue for a setpoint."""
val = self._setpoint_values[setpoint_type]
if val is None:
if (val := self._setpoint_values[setpoint_type]) is None:
raise ValueError("Value requested is not available")
return val
@ -231,8 +230,7 @@ class ZWaveClimate(ZWaveBaseEntity, ClimateEntity):
mode_id = int(mode_id)
if mode_id in THERMOSTAT_MODES:
# treat value as hvac mode
hass_mode = ZW_HVAC_MODE_MAP.get(mode_id)
if hass_mode:
if hass_mode := ZW_HVAC_MODE_MAP.get(mode_id):
all_modes[hass_mode] = mode_id
else:
# treat value as hvac preset
@ -470,8 +468,7 @@ class ZWaveClimate(ZWaveBaseEntity, ClimateEntity):
async def async_set_hvac_mode(self, hvac_mode: str) -> None:
"""Set new target hvac mode."""
hvac_mode_id = self._hvac_modes.get(hvac_mode)
if hvac_mode_id is None:
if (hvac_mode_id := self._hvac_modes.get(hvac_mode)) is None:
raise ValueError(f"Received an invalid hvac mode: {hvac_mode}")
if not self._current_mode:

View File

@ -236,8 +236,7 @@ def get_trigger_platform_from_type(trigger_type: str) -> str:
trigger_split = trigger_type.split(".")
# Our convention for trigger types is to have the trigger type at the beginning
# delimited by a `.`. For zwave_js triggers, there is a `.` in the name
trigger_platform = trigger_split[0]
if trigger_platform == DOMAIN:
if (trigger_platform := trigger_split[0]) == DOMAIN:
return ".".join(trigger_split[:2])
return trigger_platform

View File

@ -87,9 +87,8 @@ def async_get_node_from_device_id(
"""
if not dev_reg:
dev_reg = dr.async_get(hass)
device_entry = dev_reg.async_get(device_id)
if not device_entry:
if not (device_entry := dev_reg.async_get(device_id)):
raise ValueError(f"Device ID {device_id} is not valid")
# Use device config entry ID's to validate that this is a valid zwave_js device
@ -230,8 +229,7 @@ def async_get_node_status_sensor_entity_id(
ent_reg = er.async_get(hass)
if not dev_reg:
dev_reg = dr.async_get(hass)
device = dev_reg.async_get(device_id)
if not device:
if not (device := dev_reg.async_get(device_id)):
raise HomeAssistantError("Invalid Device ID provided")
entry_id = next(entry_id for entry_id in device.config_entries)

View File

@ -331,8 +331,7 @@ async def async_migrate_legacy_zwave(
ent_reg = async_get_entity_registry(hass)
for zwave_js_entity_id, zwave_entry in migration_map.entity_entries.items():
zwave_entity_id = zwave_entry["entity_id"]
entity_entry = ent_reg.async_get(zwave_entity_id)
if not entity_entry:
if not (entity_entry := ent_reg.async_get(zwave_entity_id)):
continue
ent_reg.async_remove(zwave_entity_id)
ent_reg.async_update_entity(