Use assignment expressions 24 (#58181)

This commit is contained in:
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

View file

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

View file

@ -95,8 +95,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
if not sensors: if not sensors:
return return
store = hass.data.get(DATA_ARWN) if (store := hass.data.get(DATA_ARWN)) is None:
if store is None:
store = hass.data[DATA_ARWN] = {} store = hass.data[DATA_ARWN] = {}
if isinstance(sensors, ArwnSensor): 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): def _reset_device_favorites_handler(event):
"""Handle clearing favorites on device.""" """Handle clearing favorites on device."""
token = event.data.get("token") if (token := event.data.get("token")) is None:
if token is None:
return return
doorstation = get_doorstation_by_token(hass, token) doorstation = get_doorstation_by_token(hass, token)

View file

@ -103,9 +103,7 @@ async def _async_validate_usage_stat(
) )
return return
state = hass.states.get(entity_id) if (state := hass.states.get(entity_id)) is None:
if state is None:
result.append( result.append(
ValidationIssue( ValidationIssue(
"entity_not_defined", "entity_not_defined",
@ -180,9 +178,7 @@ def _async_validate_price_entity(
unit_error: str, unit_error: str,
) -> None: ) -> None:
"""Validate that the price entity is correct.""" """Validate that the price entity is correct."""
state = hass.states.get(entity_id) if (state := hass.states.get(entity_id)) is None:
if state is None:
result.append( result.append(
ValidationIssue( ValidationIssue(
"entity_not_defined", "entity_not_defined",
@ -228,9 +224,7 @@ async def _async_validate_cost_stat(
if not recorder.is_entity_recorded(hass, stat_id): if not recorder.is_entity_recorded(hass, stat_id):
result.append(ValidationIssue("recorder_untracked", stat_id)) result.append(ValidationIssue("recorder_untracked", stat_id))
state = hass.states.get(stat_id) if (state := hass.states.get(stat_id)) is None:
if state is None:
result.append(ValidationIssue("entity_not_defined", stat_id)) result.append(ValidationIssue("entity_not_defined", stat_id))
return 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 # Override settings from YAML config, but only if they're changed in it
# Old values are stored as *_from_yaml in the config entry # Old values are stored as *_from_yaml in the config entry
yaml_config = hass.data[DOMAIN].config.get(url) if yaml_config := hass.data[DOMAIN].config.get(url):
if yaml_config:
# Config values # Config values
new_data = {} new_data = {}
for key in CONF_USERNAME, CONF_PASSWORD: for key in CONF_USERNAME, CONF_PASSWORD:

View file

@ -203,8 +203,7 @@ class HyperionConfigFlow(ConfigFlow, domain=DOMAIN):
except ValueError: except ValueError:
self._data[CONF_PORT] = const.DEFAULT_PORT_JSON self._data[CONF_PORT] = const.DEFAULT_PORT_JSON
hyperion_id = discovery_info.get(ATTR_UPNP_SERIAL) if not (hyperion_id := discovery_info.get(ATTR_UPNP_SERIAL)):
if not hyperion_id:
return self.async_abort(reason="no_id") return self.async_abort(reason="no_id")
# For discovery mechanisms, we set the unique_id as early as possible to # 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: async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Konnected platform.""" """Set up the Konnected platform."""
cfg = config.get(DOMAIN) if (cfg := config.get(DOMAIN)) is None:
if cfg is None:
cfg = {} cfg = {}
if DOMAIN not in hass.data: if DOMAIN not in hass.data:
@ -336,14 +335,12 @@ class KonnectedView(HomeAssistantView):
"updating instructions" "updating instructions"
) )
device = data[CONF_DEVICES].get(device_id) if (device := data[CONF_DEVICES].get(device_id)) is None:
if device is None:
return self.json_message( return self.json_message(
"unregistered device", status_code=HTTPStatus.BAD_REQUEST "unregistered device", status_code=HTTPStatus.BAD_REQUEST
) )
panel = device.get("panel") if (panel := device.get("panel")) is not None:
if panel is not None:
# connect if we haven't already # connect if we haven't already
hass.async_create_task(panel.async_connect()) hass.async_create_task(panel.async_connect())
@ -382,14 +379,12 @@ class KonnectedView(HomeAssistantView):
hass = request.app["hass"] hass = request.app["hass"]
data = hass.data[DOMAIN] data = hass.data[DOMAIN]
device = data[CONF_DEVICES].get(device_id) if not (device := data[CONF_DEVICES].get(device_id)):
if not device:
return self.json_message( return self.json_message(
f"Device {device_id} not configured", status_code=HTTPStatus.NOT_FOUND f"Device {device_id} not configured", status_code=HTTPStatus.NOT_FOUND
) )
panel = device.get("panel") if (panel := device.get("panel")) is not None:
if panel is not None:
# connect if we haven't already # connect if we haven't already
hass.async_create_task(panel.async_connect()) hass.async_create_task(panel.async_connect())
@ -427,8 +422,7 @@ class KonnectedView(HomeAssistantView):
resp[CONF_PIN] = ZONE_TO_PIN[zone_num] resp[CONF_PIN] = ZONE_TO_PIN[zone_num]
# Make sure entity is setup # Make sure entity is setup
zone_entity_id = zone.get(ATTR_ENTITY_ID) if zone_entity_id := zone.get(ATTR_ENTITY_ID):
if zone_entity_id:
resp["state"] = self.binary_value( resp["state"] = self.binary_value(
hass.states.get(zone_entity_id).state, zone[CONF_ACTIVATION] 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.""" """Handle an addressable sensor update."""
_LOGGER.debug("[addr handler] context: %s msg: %s", context, msg) _LOGGER.debug("[addr handler] context: %s msg: %s", context, msg)
addr, temp = msg.get("addr"), msg.get("temp") addr, temp = msg.get("addr"), msg.get("temp")
entity_id = context.get(addr) if entity_id := context.get(addr):
if entity_id:
async_dispatcher_send(hass, f"konnected.{entity_id}.update", temp) async_dispatcher_send(hass, f"konnected.{entity_id}.update", temp)
else: else:
msg["device_id"] = context.get("device_id") msg["device_id"] = context.get("device_id")

View file

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

View file

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

View file

@ -98,8 +98,7 @@ class MillHeater(CoordinatorEntity, 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 (temperature := kwargs.get(ATTR_TEMPERATURE)) is None:
if temperature is None:
return return
await self.coordinator.mill_data_connection.set_heater_temp( await self.coordinator.mill_data_connection.set_heater_temp(
self._id, int(temperature) self._id, int(temperature)

View file

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

View file

@ -176,8 +176,7 @@ class OASATelematicsData:
current_time = dt_util.utcnow() current_time = dt_util.utcnow()
for result in results: for result in results:
btime2 = result.get("btime2") if (btime2 := result.get("btime2")) is not None:
if btime2 is not None:
arrival_min = int(btime2) arrival_min = int(btime2)
timestamp = current_time + timedelta(minutes=arrival_min) timestamp = current_time + timedelta(minutes=arrival_min)
arrival_data = { 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): def _setup_scenario_switches(logger, config, scsgate, hass):
"""Add only SCSGate scenario switches.""" """Add only SCSGate scenario switches."""
scenario = config.get(CONF_SCENARIO) if scenario := config.get(CONF_SCENARIO):
if scenario:
for entity_info in scenario.values(): for entity_info in scenario.values():
if entity_info[CONF_SCS_ID] in scsgate.devices: if entity_info[CONF_SCS_ID] in scsgate.devices:
continue continue

View file

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

View file

@ -113,8 +113,7 @@ class SpiderThermostat(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 None:
if temperature is None:
return return
self.thermostat.set_temperature(temperature) self.thermostat.set_temperature(temperature)

View file

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

View file

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

View file

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

View file

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

View file

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