Use assignment expressions 15 (#57961)

pull/57967/head
Marc Mueller 2021-10-18 14:01:23 +02:00 committed by GitHub
parent a421c524c1
commit 1e98761f30
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 29 additions and 66 deletions

View File

@ -46,9 +46,7 @@ CONFIG_SCHEMA = vol.Schema(
async def async_setup(hass, config): async def async_setup(hass, config):
"""Set up the emulated roku component.""" """Set up the emulated roku component."""
conf = config.get(DOMAIN) if (conf := config.get(DOMAIN)) is None:
if conf is None:
return True return True
existing_servers = configured_servers(hass) existing_servers = configured_servers(hass)

View File

@ -161,8 +161,7 @@ class EphEmberThermostat(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
if self._hot_water: if self._hot_water:

View File

@ -64,9 +64,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"Detection: %s %s - %s", ble_device.name, ble_device, advertisement_data "Detection: %s %s - %s", ble_device.name, ble_device, advertisement_data
) )
data = state.devices.get(ble_device.address) if data := state.devices.get(ble_device.address):
if data:
data.device.detection_callback(ble_device, advertisement_data) data.device.detection_callback(ble_device, advertisement_data)
data.coordinator.async_set_updated_data(data.device.state) data.coordinator.async_set_updated_data(data.device.state)
else: else:

View File

@ -30,9 +30,7 @@ def resolve_location(hass, logger, loc):
def get_location_from_entity(hass, logger, entity_id): def get_location_from_entity(hass, logger, entity_id):
"""Get the location from the entity state or attributes.""" """Get the location from the entity state or attributes."""
entity = hass.states.get(entity_id) if (entity := hass.states.get(entity_id)) is None:
if entity is None:
logger.error("Unable to find entity %s", entity_id) logger.error("Unable to find entity %s", entity_id)
return None return None

View File

@ -149,8 +149,7 @@ class GraphiteFeeder(threading.Thread):
def run(self): def run(self):
"""Run the process to export the data.""" """Run the process to export the data."""
while True: while True:
event = self._queue.get() if (event := self._queue.get()) == self._quit_object:
if event == self._quit_object:
_LOGGER.debug("Event processing thread stopped") _LOGGER.debug("Event processing thread stopped")
self._queue.task_done() self._queue.task_done()
return return

View File

@ -227,8 +227,7 @@ class HarmonyRemote(HarmonyEntity, remote.RemoteEntity, RestoreEntity):
async def async_send_command(self, command, **kwargs): async def async_send_command(self, command, **kwargs):
"""Send a list of commands to one device.""" """Send a list of commands to one device."""
_LOGGER.debug("%s: Send Command", self.name) _LOGGER.debug("%s: Send Command", self.name)
device = kwargs.get(ATTR_DEVICE) if (device := kwargs.get(ATTR_DEVICE)) is None:
if device is None:
_LOGGER.error("%s: Missing required argument: device", self.name) _LOGGER.error("%s: Missing required argument: device", self.name)
return return

View File

@ -86,9 +86,7 @@ async def async_attach_trigger(
automation_info: AutomationTriggerInfo, automation_info: AutomationTriggerInfo,
) -> CALLBACK_TYPE: ) -> CALLBACK_TYPE:
"""Attach a trigger.""" """Attach a trigger."""
trigger_type = config[CONF_TYPE] if config[CONF_TYPE] == "target_humidity_changed":
if trigger_type == "target_humidity_changed":
numeric_state_config = { numeric_state_config = {
numeric_state_trigger.CONF_PLATFORM: "numeric_state", numeric_state_trigger.CONF_PLATFORM: "numeric_state",
numeric_state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID], numeric_state_trigger.CONF_ENTITY_ID: config[CONF_ENTITY_ID],
@ -118,9 +116,7 @@ async def async_get_trigger_capabilities(
hass: HomeAssistant, config: ConfigType hass: HomeAssistant, config: ConfigType
) -> dict[str, vol.Schema]: ) -> dict[str, vol.Schema]:
"""List trigger capabilities.""" """List trigger capabilities."""
trigger_type = config[CONF_TYPE] if config[CONF_TYPE] == "target_humidity_changed":
if trigger_type == "target_humidity_changed":
return { return {
"extra_fields": vol.Schema( "extra_fields": vol.Schema(
{ {

View File

@ -28,9 +28,7 @@ async def _async_reproduce_states(
reproduce_options: dict[str, Any] | None = None, reproduce_options: dict[str, Any] | None = None,
) -> None: ) -> None:
"""Reproduce component states.""" """Reproduce component states."""
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

@ -33,8 +33,7 @@ class MatrixNotificationService(BaseNotificationService):
"""Send the message to the Matrix server.""" """Send the message to the Matrix server."""
target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room] target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room]
service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message} service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message}
data = kwargs.get(ATTR_DATA) if (data := kwargs.get(ATTR_DATA)) is not None:
if data is not None:
service_data[ATTR_DATA] = data service_data[ATTR_DATA] = data
return self.hass.services.call( return self.hass.services.call(
DOMAIN, SERVICE_SEND_MESSAGE, service_data=service_data DOMAIN, SERVICE_SEND_MESSAGE, service_data=service_data

View File

@ -79,8 +79,7 @@ class OneWireHub:
for device_path in self.owproxy.dir(path): for device_path in self.owproxy.dir(path):
device_family = self.owproxy.read(f"{device_path}family").decode() device_family = self.owproxy.read(f"{device_path}family").decode()
device_type = self.owproxy.read(f"{device_path}type").decode() device_type = self.owproxy.read(f"{device_path}type").decode()
device_branches = DEVICE_COUPLERS.get(device_family) if device_branches := DEVICE_COUPLERS.get(device_family):
if device_branches:
for branch in device_branches: for branch in device_branches:
devices += self._discover_devices_owserver(f"{device_path}{branch}") devices += self._discover_devices_owserver(f"{device_path}{branch}")
else: else:

View File

@ -138,8 +138,7 @@ class OpenGarageCover(CoordinatorEntity, CoverEntity):
@callback @callback
def _update_attr(self) -> None: def _update_attr(self) -> None:
"""Update the state and attributes.""" """Update the state and attributes."""
status = self.coordinator.data if (status := self.coordinator.data) is None:
if status is None:
_LOGGER.error("Unable to connect to OpenGarage device") _LOGGER.error("Unable to connect to OpenGarage device")
self._attr_available = False self._attr_available = False
return return

View File

@ -109,15 +109,13 @@ async def async_get_or_create_registered_webhook_id_and_url(hass, entry):
updated_config = False updated_config = False
webhook_url = None webhook_url = None
webhook_id = config.get(CONF_WEBHOOK_ID) if not (webhook_id := config.get(CONF_WEBHOOK_ID)):
if not webhook_id:
webhook_id = hass.components.webhook.async_generate_id() webhook_id = hass.components.webhook.async_generate_id()
config[CONF_WEBHOOK_ID] = webhook_id config[CONF_WEBHOOK_ID] = webhook_id
updated_config = True updated_config = True
if hass.components.cloud.async_active_subscription(): if hass.components.cloud.async_active_subscription():
cloudhook_url = config.get(CONF_CLOUDHOOK_URL) if not (cloudhook_url := config.get(CONF_CLOUDHOOK_URL)):
if not cloudhook_url:
cloudhook_url = await hass.components.cloud.async_create_cloudhook( cloudhook_url = await hass.components.cloud.async_create_cloudhook(
webhook_id webhook_id
) )

View File

@ -94,8 +94,7 @@ class SlideCover(CoverEntity):
@property @property
def current_cover_position(self): def current_cover_position(self):
"""Return the current position of cover shutter.""" """Return the current position of cover shutter."""
pos = self._slide["pos"] if (pos := self._slide["pos"]) is not None:
if pos is not None:
if (1 - pos) <= DEFAULT_OFFSET or pos <= DEFAULT_OFFSET: if (1 - pos) <= DEFAULT_OFFSET or pos <= DEFAULT_OFFSET:
pos = round(pos) pos = round(pos)
if not self._invert: if not self._invert:

View File

@ -54,9 +54,7 @@ def setup(hass, config):
def statsd_event_listener(event): def statsd_event_listener(event):
"""Listen for new messages on the bus and sends them to StatsD.""" """Listen for new messages on the bus and sends them to StatsD."""
state = event.data.get("new_state") if (state := event.data.get("new_state")) is None:
if state is None:
return return
try: try:

View File

@ -348,8 +348,7 @@ class Stream:
raise HomeAssistantError(f"Can't write {video_path}, no access to path!") raise HomeAssistantError(f"Can't write {video_path}, no access to path!")
# Add recorder # Add recorder
recorder = self.outputs().get(RECORDER_PROVIDER) if recorder := self.outputs().get(RECORDER_PROVIDER):
if recorder:
assert isinstance(recorder, RecorderOutput) assert isinstance(recorder, RecorderOutput)
raise HomeAssistantError( raise HomeAssistantError(
f"Stream already recording to {recorder.video_path}!" f"Stream already recording to {recorder.video_path}!"

View File

@ -123,13 +123,10 @@ class TelldusLiveEntity(Entity):
"identifiers": {("tellduslive", self.device.device_id)}, "identifiers": {("tellduslive", self.device.device_id)},
"name": self.device.name, "name": self.device.name,
} }
model = device.get("model") if (model := device.get("model")) is not None:
if model is not None:
device_info["model"] = model.title() device_info["model"] = model.title()
protocol = device.get("protocol") if (protocol := device.get("protocol")) is not None:
if protocol is not None:
device_info["manufacturer"] = protocol.title() device_info["manufacturer"] = protocol.title()
client = device.get("client") if (client := device.get("client")) is not None:
if client is not None:
device_info["via_device"] = ("tellduslive", client) device_info["via_device"] = ("tellduslive", client)
return device_info return device_info

View File

@ -61,8 +61,7 @@ class VelbusClimate(VelbusEntity, ClimateEntity):
def set_temperature(self, **kwargs): def set_temperature(self, **kwargs):
"""Set new target temperatures.""" """Set new target temperatures."""
temp = kwargs.get(ATTR_TEMPERATURE) if (temp := kwargs.get(ATTR_TEMPERATURE)) is None:
if temp is None:
return return
self._channel.set_temp(temp) self._channel.set_temp(temp)
self.schedule_update_ha_state() self.schedule_update_ha_state()

View File

@ -60,8 +60,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
"""Set up the ViaggiaTreno platform.""" """Set up the ViaggiaTreno platform."""
train_id = config.get(CONF_TRAIN_ID) train_id = config.get(CONF_TRAIN_ID)
station_id = config.get(CONF_STATION_ID) station_id = config.get(CONF_STATION_ID)
name = config.get(CONF_NAME) if not (name := config.get(CONF_NAME)):
if not name:
name = DEFAULT_NAME.format(train_id) name = DEFAULT_NAME.format(train_id)
async_add_entities([ViaggiaTrenoSensor(train_id, station_id, name)]) async_add_entities([ViaggiaTrenoSensor(train_id, station_id, name)])

View File

@ -179,8 +179,7 @@ class VlcDevice(MediaPlayerEntity):
if not self._media_title: if not self._media_title:
# Fall back to filename. # Fall back to filename.
data_info = data.get("data") if data_info := data.get("data"):
if data_info:
self._media_title = data_info["filename"] self._media_title = data_info["filename"]
except CommandError as err: except CommandError as err:
@ -282,8 +281,7 @@ class VlcDevice(MediaPlayerEntity):
async def async_media_pause(self) -> None: async def async_media_pause(self) -> None:
"""Send pause command.""" """Send pause command."""
status = await self._vlc.status() status = await self._vlc.status()
current_state = status.state if status.state != "paused":
if current_state != "paused":
# Make sure we're not already paused since VLCTelnet.pause() toggles # Make sure we're not already paused since VLCTelnet.pause() toggles
# pause. # pause.
await self._vlc.pause() await self._vlc.pause()

View File

@ -29,9 +29,7 @@ def resolve_location(hass, logger, loc):
def get_location_from_entity(hass, logger, entity_id): def get_location_from_entity(hass, logger, entity_id):
"""Get the location from the entity_id.""" """Get the location from the entity_id."""
state = hass.states.get(entity_id) if (state := hass.states.get(entity_id)) is None:
if state is None:
logger.error("Unable to find entity %s", entity_id) logger.error("Unable to find entity %s", entity_id)
return None return None

View File

@ -256,8 +256,7 @@ class XiaomiMiioFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
self.cloud_devices = {} self.cloud_devices = {}
for device in devices_raw: for device in devices_raw:
parent_id = device.get("parent_id") if not device.get("parent_id"):
if not parent_id:
name = device["name"] name = device["name"]
model = device["model"] model = device["model"]
list_name = f"{name} - {model}" list_name = f"{name} - {model}"

View File

@ -229,8 +229,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
params = { params = {
key: value for key, value in service.data.items() if key != ATTR_ENTITY_ID key: value for key, value in service.data.items() if key != ATTR_ENTITY_ID
} }
entity_ids = service.data.get(ATTR_ENTITY_ID) if entity_ids := service.data.get(ATTR_ENTITY_ID):
if entity_ids:
filtered_entities = [ filtered_entities = [
entity entity
for entity in hass.data[DATA_KEY].values() for entity in hass.data[DATA_KEY].values()

View File

@ -194,8 +194,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
for key, value in service.data.items() for key, value in service.data.items()
if key != ATTR_ENTITY_ID if key != ATTR_ENTITY_ID
} }
entity_ids = service.data.get(ATTR_ENTITY_ID) if entity_ids := service.data.get(ATTR_ENTITY_ID):
if entity_ids:
target_devices = [ target_devices = [
dev dev
for dev in hass.data[DATA_KEY].values() for dev in hass.data[DATA_KEY].values()

View File

@ -414,8 +414,7 @@ async def async_setup_other_entry(hass, config_entry, async_add_entities):
for key, value in service.data.items() for key, value in service.data.items()
if key != ATTR_ENTITY_ID if key != ATTR_ENTITY_ID
} }
entity_ids = service.data.get(ATTR_ENTITY_ID) if entity_ids := service.data.get(ATTR_ENTITY_ID):
if entity_ids:
devices = [ devices = [
device device
for device in hass.data[DATA_KEY].values() for device in hass.data[DATA_KEY].values()