Use assignment expressions 24 ()

pull/58227/head
Marc Mueller 2021-10-22 14:07:19 +02:00 committed by GitHub
parent eab235173b
commit ea2e94a4e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 29 additions and 66 deletions
homeassistant/components

View File

@ -533,8 +533,7 @@ class ADBDevice(MediaPlayerEntity):
@adb_decorator()
async def adb_command(self, cmd):
"""Send an ADB command to an Android TV / Fire TV device."""
key = KEYS.get(cmd)
if key:
if key := KEYS.get(cmd):
await self.aftv.adb_shell(f"input keyevent {key}")
return

View File

@ -95,8 +95,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
if not sensors:
return
store = hass.data.get(DATA_ARWN)
if store is None:
if (store := hass.data.get(DATA_ARWN)) is None:
store = hass.data[DATA_ARWN] = {}
if isinstance(sensors, ArwnSensor):

View File

@ -68,9 +68,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
def _reset_device_favorites_handler(event):
"""Handle clearing favorites on device."""
token = event.data.get("token")
if token is None:
if (token := event.data.get("token")) is None:
return
doorstation = get_doorstation_by_token(hass, token)

View File

@ -103,9 +103,7 @@ async def _async_validate_usage_stat(
)
return
state = hass.states.get(entity_id)
if state is None:
if (state := hass.states.get(entity_id)) is None:
result.append(
ValidationIssue(
"entity_not_defined",
@ -180,9 +178,7 @@ def _async_validate_price_entity(
unit_error: str,
) -> None:
"""Validate that the price entity is correct."""
state = hass.states.get(entity_id)
if state is None:
if (state := hass.states.get(entity_id)) is None:
result.append(
ValidationIssue(
"entity_not_defined",
@ -228,9 +224,7 @@ async def _async_validate_cost_stat(
if not recorder.is_entity_recorded(hass, stat_id):
result.append(ValidationIssue("recorder_untracked", stat_id))
state = hass.states.get(stat_id)
if state is None:
if (state := hass.states.get(stat_id)) is None:
result.append(ValidationIssue("entity_not_defined", stat_id))
return

View File

@ -314,8 +314,7 @@ async def async_setup_entry( # noqa: C901
# Override settings from YAML config, but only if they're changed in it
# Old values are stored as *_from_yaml in the config entry
yaml_config = hass.data[DOMAIN].config.get(url)
if yaml_config:
if yaml_config := hass.data[DOMAIN].config.get(url):
# Config values
new_data = {}
for key in CONF_USERNAME, CONF_PASSWORD:

View File

@ -203,8 +203,7 @@ class HyperionConfigFlow(ConfigFlow, domain=DOMAIN):
except ValueError:
self._data[CONF_PORT] = const.DEFAULT_PORT_JSON
hyperion_id = discovery_info.get(ATTR_UPNP_SERIAL)
if not hyperion_id:
if not (hyperion_id := discovery_info.get(ATTR_UPNP_SERIAL)):
return self.async_abort(reason="no_id")
# For discovery mechanisms, we set the unique_id as early as possible to

View File

@ -221,8 +221,7 @@ PLATFORMS = ["binary_sensor", "sensor", "switch"]
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Konnected platform."""
cfg = config.get(DOMAIN)
if cfg is None:
if (cfg := config.get(DOMAIN)) is None:
cfg = {}
if DOMAIN not in hass.data:
@ -336,14 +335,12 @@ class KonnectedView(HomeAssistantView):
"updating instructions"
)
device = data[CONF_DEVICES].get(device_id)
if device is None:
if (device := data[CONF_DEVICES].get(device_id)) is None:
return self.json_message(
"unregistered device", status_code=HTTPStatus.BAD_REQUEST
)
panel = device.get("panel")
if panel is not None:
if (panel := device.get("panel")) is not None:
# connect if we haven't already
hass.async_create_task(panel.async_connect())
@ -382,14 +379,12 @@ class KonnectedView(HomeAssistantView):
hass = request.app["hass"]
data = hass.data[DOMAIN]
device = data[CONF_DEVICES].get(device_id)
if not device:
if not (device := data[CONF_DEVICES].get(device_id)):
return self.json_message(
f"Device {device_id} not configured", status_code=HTTPStatus.NOT_FOUND
)
panel = device.get("panel")
if panel is not None:
if (panel := device.get("panel")) is not None:
# connect if we haven't already
hass.async_create_task(panel.async_connect())
@ -427,8 +422,7 @@ class KonnectedView(HomeAssistantView):
resp[CONF_PIN] = ZONE_TO_PIN[zone_num]
# Make sure entity is setup
zone_entity_id = zone.get(ATTR_ENTITY_ID)
if zone_entity_id:
if zone_entity_id := zone.get(ATTR_ENTITY_ID):
resp["state"] = self.binary_value(
hass.states.get(zone_entity_id).state, zone[CONF_ACTIVATION]
)

View File

@ -51,8 +51,7 @@ async def async_handle_addr_update(hass, context, msg):
"""Handle an addressable sensor update."""
_LOGGER.debug("[addr handler] context: %s msg: %s", context, msg)
addr, temp = msg.get("addr"), msg.get("temp")
entity_id = context.get(addr)
if entity_id:
if entity_id := context.get(addr):
async_dispatcher_send(hass, f"konnected.{entity_id}.update", temp)
else:
msg["device_id"] = context.get("device_id")

View File

@ -347,9 +347,7 @@ class AlarmPanel:
@callback
def async_current_settings_payload(self):
"""Return a dict of configuration currently stored on the device."""
settings = self.status["settings"]
if not settings:
settings = {}
settings = self.status["settings"] or {}
return {
"sensors": [

View File

@ -110,9 +110,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
def validate_mazda_device_id(device_id):
"""Check that a device ID exists in the registry and has at least one 'mazda' identifier."""
dev_reg = device_registry.async_get(hass)
device_entry = dev_reg.async_get(device_id)
if device_entry is None:
if (device_entry := dev_reg.async_get(device_id)) is None:
raise vol.Invalid("Invalid device ID")
mazda_identifiers = [

View File

@ -98,8 +98,7 @@ class MillHeater(CoordinatorEntity, ClimateEntity):
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:
return
await self.coordinator.mill_data_connection.set_heater_temp(
self._id, int(temperature)

View File

@ -444,8 +444,7 @@ class NetatmoThermostat(NetatmoBase, ClimateEntity):
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature for 2 hours."""
temp = kwargs.get(ATTR_TEMPERATURE)
if temp is None:
if (temp := kwargs.get(ATTR_TEMPERATURE)) is None:
return
await self._home_status.async_set_room_thermpoint(
self._id, STATE_NETATMO_MANUAL, temp

View File

@ -176,8 +176,7 @@ class OASATelematicsData:
current_time = dt_util.utcnow()
for result in results:
btime2 = result.get("btime2")
if btime2 is not None:
if (btime2 := result.get("btime2")) is not None:
arrival_min = int(btime2)
timestamp = current_time + timedelta(minutes=arrival_min)
arrival_data = {

View File

@ -62,9 +62,7 @@ def _setup_traditional_switches(logger, config, scsgate, add_entities_callback):
def _setup_scenario_switches(logger, config, scsgate, hass):
"""Add only SCSGate scenario switches."""
scenario = config.get(CONF_SCENARIO)
if scenario:
if scenario := config.get(CONF_SCENARIO):
for entity_info in scenario.values():
if entity_info[CONF_SCS_ID] in scsgate.devices:
continue

View File

@ -170,9 +170,8 @@ class MailNotificationService(BaseNotificationService):
build a multipart HTML if html config is defined.
"""
subject = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
data = kwargs.get(ATTR_DATA)
if data:
if data := kwargs.get(ATTR_DATA):
if ATTR_HTML in data:
msg = _build_html_msg(
message, data[ATTR_HTML], images=data.get(ATTR_IMAGES, [])
@ -184,8 +183,7 @@ class MailNotificationService(BaseNotificationService):
msg["Subject"] = subject
recipients = kwargs.get(ATTR_TARGET)
if not recipients:
if not (recipients := kwargs.get(ATTR_TARGET)):
recipients = self.recipients
msg["To"] = recipients if isinstance(recipients, str) else ",".join(recipients)
if self._sender_name:

View File

@ -113,8 +113,7 @@ class SpiderThermostat(ClimateEntity):
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:
return
self.thermostat.set_temperature(temperature)

View File

@ -197,8 +197,7 @@ class LogErrorHandler(logging.Handler):
async def async_setup(hass, config):
"""Set up the logger component."""
conf = config.get(DOMAIN)
if conf is None:
if (conf := config.get(DOMAIN)) is None:
conf = CONFIG_SCHEMA({DOMAIN: {}})[DOMAIN]
simple_queue = queue.SimpleQueue()

View File

@ -95,8 +95,7 @@ class ThresholdSensor(BinarySensorEntity):
@callback
def async_threshold_sensor_state_listener(event):
"""Handle sensor state changes."""
new_state = event.data.get("new_state")
if new_state is None:
if (new_state := event.data.get("new_state")) is None:
return
try:

View File

@ -43,10 +43,7 @@ class TwilioCallNotificationService(BaseNotificationService):
def send_message(self, message="", **kwargs):
"""Call to specified target users."""
targets = kwargs.get(ATTR_TARGET)
if not targets:
if not (targets := kwargs.get(ATTR_TARGET)):
_LOGGER.info("At least 1 target is required")
return

View File

@ -235,8 +235,7 @@ class UnifiFlowHandler(config_entries.ConfigFlow, domain=UNIFI_DOMAIN):
CONF_SITE_ID: DEFAULT_SITE_ID,
}
port = MODEL_PORTS.get(model_description)
if port is not None:
if (port := MODEL_PORTS.get(model_description)) is not None:
self.config[CONF_PORT] = port
return await self.async_step_user()

View File

@ -54,8 +54,7 @@ class MusicCastFlowHandler(ConfigFlow, domain=DOMAIN):
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
serial_number = info.get("system_id")
if serial_number is None:
if (serial_number := info.get("system_id")) is None:
errors["base"] = "no_musiccast_device"
if not errors: