From 8d5ce5309875dad0be1ca53cf795e15681a397d3 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 27 Mar 2021 10:54:59 +0100 Subject: [PATCH] Merge of nested IF-IF cases - S-W (#48372) --- homeassistant/components/saj/sensor.py | 24 ++++++------- homeassistant/components/smhi/config_flow.py | 34 +++++++++--------- homeassistant/components/stream/hls.py | 10 +++--- .../components/subaru/config_flow.py | 29 ++++++++------- homeassistant/components/subaru/sensor.py | 22 +++++++----- .../components/systemmonitor/sensor.py | 35 +++++++------------ .../components/tado/device_tracker.py | 9 +++-- homeassistant/components/tplink/light.py | 12 +++---- .../components/unifi/device_tracker.py | 11 +++--- homeassistant/components/unifi/switch.py | 9 ++--- homeassistant/components/uvc/camera.py | 13 +++---- homeassistant/components/wilight/fan.py | 25 ++++++++----- .../components/wink/binary_sensor.py | 8 +++-- homeassistant/components/wink/sensor.py | 8 +++-- .../components/worxlandroid/sensor.py | 5 ++- 15 files changed, 128 insertions(+), 126 deletions(-) diff --git a/homeassistant/components/saj/sensor.py b/homeassistant/components/saj/sensor.py index ef69513db432..f1def71cc641 100644 --- a/homeassistant/components/saj/sensor.py +++ b/homeassistant/components/saj/sensor.py @@ -103,18 +103,18 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= for sensor in hass_sensors: state_unknown = False - if not values: - # SAJ inverters are powered by DC via solar panels and thus are - # offline after the sun has set. If a sensor resets on a daily - # basis like "today_yield", this reset won't happen automatically. - # Code below checks if today > day when sensor was last updated - # and if so: set state to None. - # Sensors with live values like "temperature" or "current_power" - # will also be reset to None. - if (sensor.per_day_basis and date.today() > sensor.date_updated) or ( - not sensor.per_day_basis and not sensor.per_total_basis - ): - state_unknown = True + # SAJ inverters are powered by DC via solar panels and thus are + # offline after the sun has set. If a sensor resets on a daily + # basis like "today_yield", this reset won't happen automatically. + # Code below checks if today > day when sensor was last updated + # and if so: set state to None. + # Sensors with live values like "temperature" or "current_power" + # will also be reset to None. + if not values and ( + (sensor.per_day_basis and date.today() > sensor.date_updated) + or (not sensor.per_day_basis and not sensor.per_total_basis) + ): + state_unknown = True sensor.async_update_values(unknown_state=state_unknown) return values diff --git a/homeassistant/components/smhi/config_flow.py b/homeassistant/components/smhi/config_flow.py index 8853680af338..a8cfdba5be55 100644 --- a/homeassistant/components/smhi/config_flow.py +++ b/homeassistant/components/smhi/config_flow.py @@ -53,31 +53,32 @@ class SmhiFlowHandler(config_entries.ConfigFlow): # If hass config has the location set and is a valid coordinate the # default location is set as default values in the form - if not smhi_locations(self.hass): - if await self._homeassistant_location_exists(): - return await self._show_config_form( - name=HOME_LOCATION_NAME, - latitude=self.hass.config.latitude, - longitude=self.hass.config.longitude, - ) + if ( + not smhi_locations(self.hass) + and await self._homeassistant_location_exists() + ): + return await self._show_config_form( + name=HOME_LOCATION_NAME, + latitude=self.hass.config.latitude, + longitude=self.hass.config.longitude, + ) return await self._show_config_form() async def _homeassistant_location_exists(self) -> bool: """Return true if default location is set and is valid.""" - if self.hass.config.latitude != 0.0 and self.hass.config.longitude != 0.0: - # Return true if valid location - if await self._check_location( + # Return true if valid location + return ( + self.hass.config.latitude != 0.0 + and self.hass.config.longitude != 0.0 + and await self._check_location( self.hass.config.longitude, self.hass.config.latitude - ): - return True - return False + ) + ) def _name_in_configuration_exists(self, name: str) -> bool: """Return True if name exists in configuration.""" - if name in smhi_locations(self.hass): - return True - return False + return name in smhi_locations(self.hass) async def _show_config_form( self, name: str = None, latitude: str = None, longitude: str = None @@ -97,7 +98,6 @@ class SmhiFlowHandler(config_entries.ConfigFlow): async def _check_location(self, longitude: str, latitude: str) -> bool: """Return true if location is ok.""" - try: session = aiohttp_client.async_get_clientsession(self.hass) smhi_api = Smhi(longitude, latitude, session=session) diff --git a/homeassistant/components/stream/hls.py b/homeassistant/components/stream/hls.py index b26009779715..4909bbf95a34 100644 --- a/homeassistant/components/stream/hls.py +++ b/homeassistant/components/stream/hls.py @@ -50,9 +50,8 @@ class HlsMasterPlaylistView(StreamView): track = stream.add_provider("hls") stream.start() # Wait for a segment to be ready - if not track.segments: - if not await track.recv(): - return web.HTTPNotFound() + if not track.segments and not await track.recv(): + return web.HTTPNotFound() headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]} return web.Response(body=self.render(track).encode("utf-8"), headers=headers) @@ -110,9 +109,8 @@ class HlsPlaylistView(StreamView): track = stream.add_provider("hls") stream.start() # Wait for a segment to be ready - if not track.segments: - if not await track.recv(): - return web.HTTPNotFound() + if not track.segments and not await track.recv(): + return web.HTTPNotFound() headers = {"Content-Type": FORMAT_CONTENT_TYPE["hls"]} return web.Response(body=self.render(track).encode("utf-8"), headers=headers) diff --git a/homeassistant/components/subaru/config_flow.py b/homeassistant/components/subaru/config_flow.py index 772134c66b16..d9d9bdff4e1e 100644 --- a/homeassistant/components/subaru/config_flow.py +++ b/homeassistant/components/subaru/config_flow.py @@ -118,21 +118,20 @@ class SubaruConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): async def async_step_pin(self, user_input=None): """Handle second part of config flow, if required.""" error = None - if user_input: - if self.controller.update_saved_pin(user_input[CONF_PIN]): - try: - vol.Match(r"[0-9]{4}")(user_input[CONF_PIN]) - await self.controller.test_pin() - except vol.Invalid: - error = {"base": "bad_pin_format"} - except InvalidPIN: - error = {"base": "incorrect_pin"} - else: - _LOGGER.debug("PIN successfully tested") - self.config_data.update(user_input) - return self.async_create_entry( - title=self.config_data[CONF_USERNAME], data=self.config_data - ) + if user_input and self.controller.update_saved_pin(user_input[CONF_PIN]): + try: + vol.Match(r"[0-9]{4}")(user_input[CONF_PIN]) + await self.controller.test_pin() + except vol.Invalid: + error = {"base": "bad_pin_format"} + except InvalidPIN: + error = {"base": "incorrect_pin"} + else: + _LOGGER.debug("PIN successfully tested") + self.config_data.update(user_input) + return self.async_create_entry( + title=self.config_data[CONF_USERNAME], data=self.config_data + ) return self.async_show_form(step_id="pin", data_schema=PIN_SCHEMA, errors=error) diff --git a/homeassistant/components/subaru/sensor.py b/homeassistant/components/subaru/sensor.py index 41dd8a6604f5..3994c9c6124f 100644 --- a/homeassistant/components/subaru/sensor.py +++ b/homeassistant/components/subaru/sensor.py @@ -220,16 +220,20 @@ class SubaruSensor(SubaruEntity, SensorEntity): self.hass.config.units.length(self.current_value, self.api_unit), 1 ) - if self.api_unit in PRESSURE_UNITS: - if self.hass.config.units == IMPERIAL_SYSTEM: - return round( - self.hass.config.units.pressure(self.current_value, self.api_unit), - 1, - ) + if ( + self.api_unit in PRESSURE_UNITS + and self.hass.config.units == IMPERIAL_SYSTEM + ): + return round( + self.hass.config.units.pressure(self.current_value, self.api_unit), + 1, + ) - if self.api_unit in FUEL_CONSUMPTION_UNITS: - if self.hass.config.units == IMPERIAL_SYSTEM: - return round((100.0 * L_PER_GAL) / (KM_PER_MI * self.current_value), 1) + if ( + self.api_unit in FUEL_CONSUMPTION_UNITS + and self.hass.config.units == IMPERIAL_SYSTEM + ): + return round((100.0 * L_PER_GAL) / (KM_PER_MI * self.current_value), 1) return self.current_value diff --git a/homeassistant/components/systemmonitor/sensor.py b/homeassistant/components/systemmonitor/sensor.py index 3e69939cbf32..596f56d51a14 100644 --- a/homeassistant/components/systemmonitor/sensor.py +++ b/homeassistant/components/systemmonitor/sensor.py @@ -164,17 +164,18 @@ def setup_platform(hass, config, add_entities, discovery_info=None): # Initialize the sensor argument if none was provided. # For disk monitoring default to "/" (root) to prevent runtime errors, if argument was not specified. if CONF_ARG not in resource: + resource[CONF_ARG] = "" if resource[CONF_TYPE].startswith("disk_"): resource[CONF_ARG] = "/" - else: - resource[CONF_ARG] = "" # Verify if we can retrieve CPU / processor temperatures. # If not, do not create the entity and add a warning to the log - if resource[CONF_TYPE] == "processor_temperature": - if SystemMonitorSensor.read_cpu_temperature() is None: - _LOGGER.warning("Cannot read CPU / processor temperature information") - continue + if ( + resource[CONF_TYPE] == "processor_temperature" + and SystemMonitorSensor.read_cpu_temperature() is None + ): + _LOGGER.warning("Cannot read CPU / processor temperature information") + continue dev.append(SystemMonitorSensor(resource[CONF_TYPE], resource[CONF_ARG])) @@ -272,23 +273,20 @@ class SystemMonitorSensor(SensorEntity): err.name, ) self._state = STATE_OFF - elif self.type == "network_out" or self.type == "network_in": + elif self.type in ["network_out", "network_in"]: counters = psutil.net_io_counters(pernic=True) if self.argument in counters: counter = counters[self.argument][IO_COUNTER[self.type]] self._state = round(counter / 1024 ** 2, 1) else: self._state = None - elif self.type == "packets_out" or self.type == "packets_in": + elif self.type in ["packets_out", "packets_in"]: counters = psutil.net_io_counters(pernic=True) if self.argument in counters: self._state = counters[self.argument][IO_COUNTER[self.type]] else: self._state = None - elif ( - self.type == "throughput_network_out" - or self.type == "throughput_network_in" - ): + elif self.type in ["throughput_network_out", "throughput_network_in"]: counters = psutil.net_io_counters(pernic=True) if self.argument in counters: counter = counters[self.argument][IO_COUNTER[self.type]] @@ -306,7 +304,7 @@ class SystemMonitorSensor(SensorEntity): self._last_value = counter else: self._state = None - elif self.type == "ipv4_address" or self.type == "ipv6_address": + elif self.type in ["ipv4_address", "ipv6_address"]: addresses = psutil.net_if_addrs() if self.argument in addresses: for addr in addresses[self.argument]: @@ -333,16 +331,9 @@ class SystemMonitorSensor(SensorEntity): temps = psutil.sensors_temperatures() for name, entries in temps.items(): - i = 1 - for entry in entries: + for i, entry in enumerate(entries, start=1): # In case the label is empty (e.g. on Raspberry PI 4), # construct it ourself here based on the sensor key name. - if not entry.label: - _label = f"{name} {i}" - else: - _label = entry.label - + _label = f"{name} {i}" if not entry.label else entry.label if _label in CPU_SENSOR_PREFIXES: return round(entry.current, 1) - - i += 1 diff --git a/homeassistant/components/tado/device_tracker.py b/homeassistant/components/tado/device_tracker.py index 8de938af9857..afa8bc6a604a 100644 --- a/homeassistant/components/tado/device_tracker.py +++ b/homeassistant/components/tado/device_tracker.py @@ -131,11 +131,10 @@ class TadoDeviceScanner(DeviceScanner): # Find devices that have geofencing enabled, and are currently at home. for mobile_device in tado_json: - if mobile_device.get("location"): - if mobile_device["location"]["atHome"]: - device_id = mobile_device["id"] - device_name = mobile_device["name"] - last_results.append(Device(device_id, device_name)) + if mobile_device.get("location") and mobile_device["location"]["atHome"]: + device_id = mobile_device["id"] + device_name = mobile_device["name"] + last_results.append(Device(device_id, device_name)) self.last_results = last_results diff --git a/homeassistant/components/tplink/light.py b/homeassistant/components/tplink/light.py index 3cb7e6630580..9a55e644e797 100644 --- a/homeassistant/components/tplink/light.py +++ b/homeassistant/components/tplink/light.py @@ -320,12 +320,12 @@ class TPLinkSmartBulb(LightEntity): light_state_params[LIGHT_STATE_BRIGHTNESS] ) - if light_features.supported_features & SUPPORT_COLOR_TEMP: - if ( - light_state_params.get(LIGHT_STATE_COLOR_TEMP) is not None - and light_state_params[LIGHT_STATE_COLOR_TEMP] != 0 - ): - color_temp = kelvin_to_mired(light_state_params[LIGHT_STATE_COLOR_TEMP]) + if ( + light_features.supported_features & SUPPORT_COLOR_TEMP + and light_state_params.get(LIGHT_STATE_COLOR_TEMP) is not None + and light_state_params[LIGHT_STATE_COLOR_TEMP] != 0 + ): + color_temp = kelvin_to_mired(light_state_params[LIGHT_STATE_COLOR_TEMP]) if light_features.supported_features & SUPPORT_COLOR: hue_saturation = ( diff --git a/homeassistant/components/unifi/device_tracker.py b/homeassistant/components/unifi/device_tracker.py index dddb4d0e5e32..9842184e2ee5 100644 --- a/homeassistant/components/unifi/device_tracker.py +++ b/homeassistant/components/unifi/device_tracker.py @@ -205,10 +205,13 @@ class UniFiClientTracker(UniFiClient, ScannerEntity): elif not self.heartbeat_check: self.schedule_update = True - elif not self.client.event and self.client.last_updated == SOURCE_DATA: - if self.is_wired == self.client.is_wired: - self._is_connected = True - self.schedule_update = True + elif ( + not self.client.event + and self.client.last_updated == SOURCE_DATA + and self.is_wired == self.client.is_wired + ): + self._is_connected = True + self.schedule_update = True if self.schedule_update: self.schedule_update = False diff --git a/homeassistant/components/unifi/switch.py b/homeassistant/components/unifi/switch.py index da3139317d17..f04acaaec872 100644 --- a/homeassistant/components/unifi/switch.py +++ b/homeassistant/components/unifi/switch.py @@ -279,10 +279,11 @@ class UniFiBlockClientSwitch(UniFiClient, SwitchEntity): @callback def async_update_callback(self) -> None: """Update the clients state.""" - if self.client.last_updated == SOURCE_EVENT: - - if self.client.event.event in CLIENT_BLOCKED + CLIENT_UNBLOCKED: - self._is_blocked = self.client.event.event in CLIENT_BLOCKED + if ( + self.client.last_updated == SOURCE_EVENT + and self.client.event.event in CLIENT_BLOCKED + CLIENT_UNBLOCKED + ): + self._is_blocked = self.client.event.event in CLIENT_BLOCKED super().async_update_callback() diff --git a/homeassistant/components/uvc/camera.py b/homeassistant/components/uvc/camera.py index 367a3915e6de..6bbd868a8bde 100644 --- a/homeassistant/components/uvc/camera.py +++ b/homeassistant/components/uvc/camera.py @@ -129,11 +129,9 @@ class UnifiVideoCamera(Camera): if "recordingIndicator" in self._caminfo: recording_state = self._caminfo["recordingIndicator"] - return ( - self._caminfo["recordingSettings"]["fullTimeRecordEnabled"] - or recording_state == "MOTION_INPROGRESS" - or recording_state == "MOTION_FINISHED" - ) + return self._caminfo["recordingSettings"][ + "fullTimeRecordEnabled" + ] or recording_state in ["MOTION_INPROGRESS", "MOTION_FINISHED"] @property def motion_detection_enabled(self): @@ -198,9 +196,8 @@ class UnifiVideoCamera(Camera): def camera_image(self): """Return the image of this camera.""" - if not self._camera: - if not self._login(): - return + if not self._camera and not self._login(): + return def _get_image(retry=True): try: diff --git a/homeassistant/components/wilight/fan.py b/homeassistant/components/wilight/fan.py index 49402ecb9112..e55413926ac3 100644 --- a/homeassistant/components/wilight/fan.py +++ b/homeassistant/components/wilight/fan.py @@ -80,9 +80,12 @@ class WiLightFan(WiLightDevice, FanEntity): @property def percentage(self) -> int | None: """Return the current speed percentage.""" - if "direction" in self._status: - if self._status["direction"] == WL_DIRECTION_OFF: - return 0 + if ( + "direction" in self._status + and self._status["direction"] == WL_DIRECTION_OFF + ): + return 0 + wl_speed = self._status.get("speed") if wl_speed is None: return None @@ -96,9 +99,11 @@ class WiLightFan(WiLightDevice, FanEntity): @property def current_direction(self) -> str: """Return the current direction of the fan.""" - if "direction" in self._status: - if self._status["direction"] != WL_DIRECTION_OFF: - self._direction = self._status["direction"] + if ( + "direction" in self._status + and self._status["direction"] != WL_DIRECTION_OFF + ): + self._direction = self._status["direction"] return self._direction async def async_turn_on( @@ -119,9 +124,11 @@ class WiLightFan(WiLightDevice, FanEntity): if percentage == 0: await self._client.set_fan_direction(self._index, WL_DIRECTION_OFF) return - if "direction" in self._status: - if self._status["direction"] == WL_DIRECTION_OFF: - await self._client.set_fan_direction(self._index, self._direction) + if ( + "direction" in self._status + and self._status["direction"] == WL_DIRECTION_OFF + ): + await self._client.set_fan_direction(self._index, self._direction) wl_speed = percentage_to_ordered_list_item(ORDERED_NAMED_FAN_SPEEDS, percentage) await self._client.set_fan_speed(self._index, wl_speed) diff --git a/homeassistant/components/wink/binary_sensor.py b/homeassistant/components/wink/binary_sensor.py index ea864e912f02..6a5977c1dc26 100644 --- a/homeassistant/components/wink/binary_sensor.py +++ b/homeassistant/components/wink/binary_sensor.py @@ -40,9 +40,11 @@ def setup_platform(hass, config, add_entities, discovery_info=None): for sensor in pywink.get_sensors(): _id = sensor.object_id() + sensor.name() - if _id not in hass.data[DOMAIN]["unique_ids"]: - if sensor.capability() in SENSOR_TYPES: - add_entities([WinkBinarySensorEntity(sensor, hass)]) + if ( + _id not in hass.data[DOMAIN]["unique_ids"] + and sensor.capability() in SENSOR_TYPES + ): + add_entities([WinkBinarySensorEntity(sensor, hass)]) for key in pywink.get_keys(): _id = key.object_id() + key.name() diff --git a/homeassistant/components/wink/sensor.py b/homeassistant/components/wink/sensor.py index 8d60c21c1188..f640a24def22 100644 --- a/homeassistant/components/wink/sensor.py +++ b/homeassistant/components/wink/sensor.py @@ -19,9 +19,11 @@ def setup_platform(hass, config, add_entities, discovery_info=None): for sensor in pywink.get_sensors(): _id = sensor.object_id() + sensor.name() - if _id not in hass.data[DOMAIN]["unique_ids"]: - if sensor.capability() in SENSOR_TYPES: - add_entities([WinkSensorEntity(sensor, hass)]) + if ( + _id not in hass.data[DOMAIN]["unique_ids"] + and sensor.capability() in SENSOR_TYPES + ): + add_entities([WinkSensorEntity(sensor, hass)]) for eggtray in pywink.get_eggtrays(): _id = eggtray.object_id() + eggtray.name() diff --git a/homeassistant/components/worxlandroid/sensor.py b/homeassistant/components/worxlandroid/sensor.py index 9be3afabc9f3..e7600670c522 100644 --- a/homeassistant/components/worxlandroid/sensor.py +++ b/homeassistant/components/worxlandroid/sensor.py @@ -127,9 +127,8 @@ class WorxLandroidSensor(SensorEntity): def get_error(obj): """Get the mower error.""" for i, err in enumerate(obj["allarmi"]): - if i != 2: # ignore wire bounce errors - if err == 1: - return ERROR_STATE[i] + if i != 2 and err == 1: # ignore wire bounce errors + return ERROR_STATE[i] return None