Use assignment expressions 20 (#57969)

This commit is contained in:
Marc Mueller 2021-10-20 20:31:00 +02:00 committed by GitHub
parent 398061706c
commit 487fa0a905
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 29 additions and 52 deletions

View file

@ -131,8 +131,7 @@ class BuienradarCam(Camera):
_LOGGER.debug("HTTP 304 - success") _LOGGER.debug("HTTP 304 - success")
return True return True
last_modified = res.headers.get("Last-Modified") if last_modified := res.headers.get("Last-Modified"):
if last_modified:
self._last_modified = last_modified self._last_modified = last_modified
self._last_image = await res.read() self._last_image = await res.read()

View file

@ -786,8 +786,7 @@ class BrSensor(SensorEntity):
if sensor_type == SYMBOL or sensor_type.startswith(CONDITION): if sensor_type == SYMBOL or sensor_type.startswith(CONDITION):
# update weather symbol & status text # update weather symbol & status text
condition = data.get(CONDITION) if condition := data.get(CONDITION):
if condition:
if sensor_type == SYMBOL: if sensor_type == SYMBOL:
new_state = condition.get(EXACTNL) new_state = condition.get(EXACTNL)
if sensor_type == CONDITION: if sensor_type == CONDITION:

View file

@ -133,11 +133,12 @@ class BrWeather(WeatherEntity):
@property @property
def condition(self): def condition(self):
"""Return the current condition.""" """Return the current condition."""
if self._data and self._data.condition: if (
ccode = self._data.condition.get(CONDCODE) self._data
if ccode: and self._data.condition
conditions = self.hass.data[DOMAIN].get(DATA_CONDITION) and (ccode := self._data.condition.get(CONDCODE))
if conditions: and (conditions := self.hass.data[DOMAIN].get(DATA_CONDITION))
):
return conditions.get(ccode) return conditions.get(ccode)
@property @property

View file

@ -48,8 +48,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
debugpy.listen((conf[CONF_HOST], conf[CONF_PORT])) debugpy.listen((conf[CONF_HOST], conf[CONF_PORT]))
wait = conf[CONF_WAIT] if conf[CONF_WAIT]:
if wait:
_LOGGER.warning( _LOGGER.warning(
"Waiting for remote debug connection on %s:%s", "Waiting for remote debug connection on %s:%s",
conf[CONF_HOST], conf[CONF_HOST],

View file

@ -598,8 +598,7 @@ class MQTT:
""" """
self = hass.data[DATA_MQTT] self = hass.data[DATA_MQTT]
conf = hass.data.get(DATA_MQTT_CONFIG) if (conf := hass.data.get(DATA_MQTT_CONFIG)) is None:
if conf is None:
conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN] conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN]
self.conf = _merge_config(entry, conf) self.conf = _merge_config(entry, conf)
@ -622,8 +621,7 @@ class MQTT:
else: else:
proto = mqtt.MQTTv311 proto = mqtt.MQTTv311
client_id = self.conf.get(CONF_CLIENT_ID) if (client_id := self.conf.get(CONF_CLIENT_ID)) is None:
if client_id is None:
# PAHO MQTT relies on the MQTT server to generate random client IDs. # PAHO MQTT relies on the MQTT server to generate random client IDs.
# However, that feature is not mandatory so we generate our own. # However, that feature is not mandatory so we generate our own.
client_id = mqtt.base62(uuid.uuid4().int, padding=22) client_id = mqtt.base62(uuid.uuid4().int, padding=22)
@ -637,9 +635,7 @@ class MQTT:
if username is not None: if username is not None:
self._mqttc.username_pw_set(username, password) self._mqttc.username_pw_set(username, password)
certificate = self.conf.get(CONF_CERTIFICATE) if (certificate := self.conf.get(CONF_CERTIFICATE)) == "auto":
if certificate == "auto":
certificate = certifi.where() certificate = certifi.where()
client_key = self.conf.get(CONF_CLIENT_KEY) client_key = self.conf.get(CONF_CLIENT_KEY)
@ -1002,8 +998,7 @@ async def websocket_remove_device(hass, connection, msg):
device_id = msg["device_id"] device_id = msg["device_id"]
dev_registry = await hass.helpers.device_registry.async_get_registry() dev_registry = await hass.helpers.device_registry.async_get_registry()
device = dev_registry.async_get(device_id) if not (device := dev_registry.async_get(device_id)):
if not device:
connection.send_error( connection.send_error(
msg["id"], websocket_api.const.ERR_NOT_FOUND, "Device not found" msg["id"], websocket_api.const.ERR_NOT_FOUND, "Device not found"
) )

View file

@ -205,8 +205,7 @@ class MqttAlarm(MqttEntity, alarm.AlarmControlPanelEntity):
@property @property
def code_format(self): def code_format(self):
"""Return one or more digits/characters.""" """Return one or more digits/characters."""
code = self._config.get(CONF_CODE) if (code := self._config.get(CONF_CODE)) is None:
if code is None:
return None return None
if code == REMOTE_CODE or (isinstance(code, str) and re.search("^\\d+$", code)): if code == REMOTE_CODE or (isinstance(code, str) and re.search("^\\d+$", code)):
return alarm.FORMAT_NUMBER return alarm.FORMAT_NUMBER

View file

@ -142,8 +142,7 @@ async def async_start( # noqa: C901
payload[key] = f"{value[:-1]}{base}" payload[key] = f"{value[:-1]}{base}"
if payload.get(CONF_AVAILABILITY): if payload.get(CONF_AVAILABILITY):
for availability_conf in payload[CONF_AVAILABILITY]: for availability_conf in payload[CONF_AVAILABILITY]:
topic = availability_conf.get(CONF_TOPIC) if topic := availability_conf.get(CONF_TOPIC):
if topic:
if topic[0] == TOPIC_BASE: if topic[0] == TOPIC_BASE:
availability_conf[CONF_TOPIC] = f"{base}{topic[1:]}" availability_conf[CONF_TOPIC] = f"{base}{topic[1:]}"
if topic[-1] == TOPIC_BASE: if topic[-1] == TOPIC_BASE:

View file

@ -826,8 +826,7 @@ class MqttLight(MqttEntity, LightEntity, RestoreEntity):
def render_rgbx(color, template, color_mode): def render_rgbx(color, template, color_mode):
"""Render RGBx payload.""" """Render RGBx payload."""
tpl = self._command_templates[template] if tpl := self._command_templates[template]:
if tpl:
keys = ["red", "green", "blue"] keys = ["red", "green", "blue"]
if color_mode == COLOR_MODE_RGBW: if color_mode == COLOR_MODE_RGBW:
keys.append("white") keys.append("white")

View file

@ -31,8 +31,7 @@ async def async_setup_entry(hass, config_entry):
hass.config_entries.async_setup_platforms(config_entry, PLATFORMS) hass.config_entries.async_setup_platforms(config_entry, PLATFORMS)
def _element_changed(element, changeset): def _element_changed(element, changeset):
change = changeset.get("last_change") if (change := changeset.get("last_change")) is None:
if change is None:
return return
if change.get("command") is None: if change.get("command") is None:
return return

View file

@ -62,8 +62,7 @@ async def _validate_input(data):
def _make_url_from_data(data): def _make_url_from_data(data):
host = data.get(CONF_HOST) if host := data.get(CONF_HOST):
if host:
return host return host
protocol = PROTOCOL_MAP[data[CONF_PROTOCOL]] protocol = PROTOCOL_MAP[data[CONF_PROTOCOL]]

View file

@ -67,8 +67,7 @@ class UpbLight(UpbAttachedEntity, LightEntity):
async def async_turn_on(self, **kwargs): async def async_turn_on(self, **kwargs):
"""Turn on the light.""" """Turn on the light."""
flash = kwargs.get(ATTR_FLASH) if flash := kwargs.get(ATTR_FLASH):
if flash:
await self.async_light_blink(0.5 if flash == "short" else 1.5) await self.async_light_blink(0.5 if flash == "short" else 1.5)
else: else:
rate = kwargs.get(ATTR_TRANSITION, -1) rate = kwargs.get(ATTR_TRANSITION, -1)

View file

@ -139,8 +139,7 @@ class ElectricalMeasurementChannel(ZigbeeChannel):
@property @property
def measurement_type(self) -> str | None: def measurement_type(self) -> str | None:
"""Return Measurement type.""" """Return Measurement type."""
meas_type = self.cluster.get("measurement_type") if (meas_type := self.cluster.get("measurement_type")) is None:
if meas_type is None:
return None return None
meas_type = self.MeasurementType(meas_type) meas_type = self.MeasurementType(meas_type)

View file

@ -138,8 +138,7 @@ class Metering(ZigbeeChannel):
@property @property
def status(self) -> int | None: def status(self) -> int | None:
"""Return metering device status.""" """Return metering device status."""
status = self.cluster.get("status") if (status := self.cluster.get("status")) is None:
if status is None:
return None return None
if self.cluster.get("metering_device_type") == 0: if self.cluster.get("metering_device_type") == 0:
# Electric metering device type # Electric metering device type

View file

@ -206,8 +206,7 @@ class ProbeEndpoint:
def initialize(self, hass: HomeAssistant) -> None: def initialize(self, hass: HomeAssistant) -> None:
"""Update device overrides config.""" """Update device overrides config."""
zha_config = hass.data[zha_const.DATA_ZHA].get(zha_const.DATA_ZHA_CONFIG, {}) zha_config = hass.data[zha_const.DATA_ZHA].get(zha_const.DATA_ZHA_CONFIG, {})
overrides = zha_config.get(zha_const.CONF_DEVICE_CONFIG) if overrides := zha_config.get(zha_const.CONF_DEVICE_CONFIG):
if overrides:
self._device_configs.update(overrides) self._device_configs.update(overrides)
@ -237,8 +236,7 @@ class GroupProbe:
def _reprobe_group(self, group_id: int) -> None: def _reprobe_group(self, group_id: int) -> None:
"""Reprobe a group for entities after its members change.""" """Reprobe a group for entities after its members change."""
zha_gateway = self._hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY] zha_gateway = self._hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY]
zha_group = zha_gateway.groups.get(group_id) if (zha_group := zha_gateway.groups.get(group_id)) is None:
if zha_group is None:
return return
self.discover_group_entities(zha_group) self.discover_group_entities(zha_group)

View file

@ -494,8 +494,7 @@ class ZHAGateway:
self, zigpy_device: zha_typing.ZigpyDeviceType, restored: bool = False self, zigpy_device: zha_typing.ZigpyDeviceType, restored: bool = False
): ):
"""Get or create a ZHA device.""" """Get or create a ZHA device."""
zha_device = self._devices.get(zigpy_device.ieee) if (zha_device := self._devices.get(zigpy_device.ieee)) is None:
if zha_device is None:
zha_device = ZHADevice.new(self._hass, zigpy_device, self, restored) zha_device = ZHADevice.new(self._hass, zigpy_device, self, restored)
self._devices[zigpy_device.ieee] = zha_device self._devices[zigpy_device.ieee] = zha_device
device_registry_device = self.ha_device_registry.async_get_or_create( device_registry_device = self.ha_device_registry.async_get_or_create(
@ -649,8 +648,7 @@ class ZHAGateway:
async def async_remove_zigpy_group(self, group_id: int) -> None: async def async_remove_zigpy_group(self, group_id: int) -> None:
"""Remove a Zigbee group from Zigpy.""" """Remove a Zigbee group from Zigpy."""
group = self.groups.get(group_id) if not (group := self.groups.get(group_id)):
if not group:
_LOGGER.debug("Group: %s:0x%04x could not be found", group.name, group_id) _LOGGER.debug("Group: %s:0x%04x could not be found", group.name, group_id)
return return
if group.members: if group.members:

View file

@ -167,8 +167,7 @@ async def async_get_zha_device(hass, device_id):
def find_state_attributes(states: list[State], key: str) -> Iterator[Any]: def find_state_attributes(states: list[State], key: str) -> Iterator[Any]:
"""Find attributes with matching key from states.""" """Find attributes with matching key from states."""
for state in states: for state in states:
value = state.attributes.get(key) if (value := state.attributes.get(key)) is not None:
if value is not None:
yield value yield value

View file

@ -131,9 +131,7 @@ class ZhaStorage:
@bind_hass @bind_hass
async def async_get_registry(hass: HomeAssistant) -> ZhaStorage: async def async_get_registry(hass: HomeAssistant) -> ZhaStorage:
"""Return zha device storage instance.""" """Return zha device storage instance."""
task = hass.data.get(DATA_REGISTRY) if (task := hass.data.get(DATA_REGISTRY)) is None:
if task is None:
async def _load_reg() -> ZhaStorage: async def _load_reg() -> ZhaStorage:
registry = ZhaStorage(hass) registry = ZhaStorage(hass)

View file

@ -481,8 +481,7 @@ class Light(BaseLight, ZhaEntity):
attributes, from_cache=False attributes, from_cache=False
) )
color_mode = results.get("color_mode") if (color_mode := results.get("color_mode")) is not None:
if color_mode is not None:
if color_mode == LightColorMode.COLOR_TEMP: if color_mode == LightColorMode.COLOR_TEMP:
color_temp = results.get("color_temperature") color_temp = results.get("color_temperature")
if color_temp is not None and color_mode: if color_temp is not None and color_mode: