Replace lists with tuples (2) (#53685)

This commit is contained in:
Marc Mueller 2021-07-30 01:20:03 +02:00 committed by GitHub
parent 5eba3e485b
commit 0815eede4b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
61 changed files with 137 additions and 139 deletions

View file

@ -61,7 +61,7 @@ class AcmedaCover(AcmedaBase, CoverEntity):
None is unknown, 0 is closed, 100 is fully open.
"""
position = None
if self.roller.type in [7, 10]:
if self.roller.type in (7, 10):
position = 100 - self.roller.closed_percent
return position

View file

@ -156,10 +156,10 @@ async def async_setup_entry(
coordinator = hass.data[DOMAIN][DATA_COORDINATOR][config_entry.entry_id]
sensors: list[AirVisualGeographySensor | AirVisualNodeProSensor]
if config_entry.data[CONF_INTEGRATION_TYPE] in [
if config_entry.data[CONF_INTEGRATION_TYPE] in (
INTEGRATION_TYPE_GEOGRAPHY_COORDS,
INTEGRATION_TYPE_GEOGRAPHY_NAME,
]:
):
sensors = [
AirVisualGeographySensor(
coordinator,

View file

@ -456,7 +456,7 @@ class ADBDevice(MediaPlayerEntity):
async def async_get_media_image(self):
"""Fetch current playing image."""
if not self._screencap or self.state in [STATE_OFF, None] or not self.available:
if not self._screencap or self.state in (STATE_OFF, None) or not self.available:
return None, None
self._attr_media_image_hash = (
f"{datetime.now().timestamp()}" if self._screencap else None

View file

@ -37,18 +37,18 @@ class AtagSensor(AtagEntity, SensorEntity):
"""Initialize Atag sensor."""
super().__init__(coordinator, SENSORS[sensor])
self._attr_name = sensor
if coordinator.data.report[self._id].sensorclass in [
if coordinator.data.report[self._id].sensorclass in (
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
]:
):
self._attr_device_class = coordinator.data.report[self._id].sensorclass
if coordinator.data.report[self._id].measure in [
if coordinator.data.report[self._id].measure in (
PRESSURE_BAR,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
PERCENTAGE,
TIME_HOURS,
]:
):
self._attr_unit_of_measurement = coordinator.data.report[self._id].measure
@property

View file

@ -248,10 +248,10 @@ class LoginFlowResourceView(HomeAssistantView):
if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY:
# @log_invalid_auth does not work here since it returns HTTP 200
# need manually log failed login attempts
if result.get("errors") is not None and result["errors"].get("base") in [
if result.get("errors") is not None and result["errors"].get("base") in (
"invalid_auth",
"invalid_code",
]:
):
await process_wrong_login(request)
return self.json(_prepare_result_json(result))

View file

@ -255,7 +255,7 @@ class ChannelsPlayer(MediaPlayerEntity):
if media_type == MEDIA_TYPE_CHANNEL:
response = self.client.play_channel(media_id)
self.update_state(response)
elif media_type in [MEDIA_TYPE_MOVIE, MEDIA_TYPE_EPISODE, MEDIA_TYPE_TVSHOW]:
elif media_type in (MEDIA_TYPE_MOVIE, MEDIA_TYPE_EPISODE, MEDIA_TYPE_TVSHOW):
response = self.client.play_recording(media_id)
self.update_state(response)

View file

@ -136,8 +136,8 @@ class DerivativeSensor(RestoreEntity, SensorEntity):
new_state = event.data.get("new_state")
if (
old_state is None
or old_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
or new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
or old_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE)
or new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE)
):
return

View file

@ -31,11 +31,11 @@ async def async_setup_entry(
for gateway in hass.data[DOMAIN][entry.entry_id]["gateways"]:
for device in gateway.multi_level_switch_devices:
for multi_level_switch in device.multi_level_switch_property:
if device.device_model_uid in [
if device.device_model_uid in (
"devolo.model.Thermostat:Valve",
"devolo.model.Room:Thermostat",
"devolo.model.Eurotronic:Spirit:Device",
]:
):
entities.append(
DevoloClimateDeviceEntity(
homecontrol=gateway,

View file

@ -21,7 +21,7 @@ _LOGGER: Final = logging.getLogger(__name__)
def host_valid(host: str) -> bool:
"""Return True if hostname or IP address is valid."""
try:
if ipaddress.ip_address(host).version in [4, 6]:
if ipaddress.ip_address(host).version in (4, 6):
return True
except ValueError:
pass

View file

@ -109,11 +109,11 @@ class EcobeeSensor(SensorEntity):
@property
def state(self):
"""Return the state of the sensor."""
if self._state in [
if self._state in (
ECOBEE_STATE_CALIBRATING,
ECOBEE_STATE_UNKNOWN,
"unknown",
]:
):
return None
if self.type == "temperature":

View file

@ -137,10 +137,10 @@ class ECSensor(SensorEntity):
else:
self._state = value
if sensor_data.get("unit") == "C" or self.sensor_type in [
if sensor_data.get("unit") == "C" or self.sensor_type in (
"wind_chill",
"humidex",
]:
):
self._unit = TEMP_CELSIUS
self._device_class = DEVICE_CLASS_TEMPERATURE
else:

View file

@ -111,10 +111,10 @@ class EsphomeFlowHandler(ConfigFlow, domain=DOMAIN):
for entry in self._async_current_entries():
already_configured = False
if CONF_HOST in entry.data and entry.data[CONF_HOST] in [
if CONF_HOST in entry.data and entry.data[CONF_HOST] in (
address,
discovery_info[CONF_HOST],
]:
):
# Is this address or IP address already configured?
already_configured = True
elif DomainData.get(self.hass).is_entry_loaded(entry):

View file

@ -531,7 +531,7 @@ class EvoDevice(Entity):
return
if payload["unique_id"] != self._unique_id:
return
if payload["service"] in [SVC_SET_ZONE_OVERRIDE, SVC_RESET_ZONE_OVERRIDE]:
if payload["service"] in (SVC_SET_ZONE_OVERRIDE, SVC_RESET_ZONE_OVERRIDE):
await self.async_zone_svc_request(payload["service"], payload["data"])
return
await self.async_tcs_svc_request(payload["service"], payload["data"])

View file

@ -194,7 +194,7 @@ class EvoZone(EvoChild, EvoClimateEntity):
@property
def hvac_mode(self) -> str:
"""Return the current operating mode of a Zone."""
if self._evo_tcs.systemModeStatus["mode"] in [EVO_AWAY, EVO_HEATOFF]:
if self._evo_tcs.systemModeStatus["mode"] in (EVO_AWAY, EVO_HEATOFF):
return HVAC_MODE_AUTO
is_off = self.target_temperature <= self.min_temp
return HVAC_MODE_OFF if is_off else HVAC_MODE_HEAT
@ -207,7 +207,7 @@ class EvoZone(EvoChild, EvoClimateEntity):
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode, e.g., home, away, temp."""
if self._evo_tcs.systemModeStatus["mode"] in [EVO_AWAY, EVO_HEATOFF]:
if self._evo_tcs.systemModeStatus["mode"] in (EVO_AWAY, EVO_HEATOFF):
return TCS_PRESET_TO_HA.get(self._evo_tcs.systemModeStatus["mode"])
return EVO_PRESET_TO_HA.get(self._evo_device.setpointStatus["setpointMode"])

View file

@ -209,7 +209,7 @@ class SensorFilter(SensorEntity):
self.async_write_ha_state()
return
if new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]:
if new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE):
self._state = new_state.state
self.async_write_ha_state()
return

View file

@ -152,8 +152,8 @@ class IntegrationSensor(RestoreEntity, SensorEntity):
new_state = event.data.get("new_state")
if (
old_state is None
or old_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
or new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]
or old_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE)
or new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE)
):
return

View file

@ -397,7 +397,7 @@ class ISYBinarySensorHeartbeat(ISYNodeEntity, BinarySensorEntity):
The ISY uses both DON and DOF commands (alternating) for a heartbeat.
"""
if event.control in [CMD_ON, CMD_OFF]:
if event.control in (CMD_ON, CMD_OFF):
self.async_heartbeat()
@callback

View file

@ -114,10 +114,10 @@ def _check_for_insteon_type(
return True
# Thermostats, which has a "Heat" and "Cool" sub-node on address 2 and 3
if platform == CLIMATE and subnode_id in [
if platform == CLIMATE and subnode_id in (
SUBNODE_CLIMATE_COOL,
SUBNODE_CLIMATE_HEAT,
]:
):
hass_isy_data[ISY994_NODES][BINARY_SENSOR].append(node)
return True
@ -184,7 +184,7 @@ def _check_for_uom_id(
This is used for versions of the ISY firmware that report uoms as a single
ID. We can often infer what type of device it is by that ID.
"""
if not hasattr(node, "uom") or node.uom in [None, ""]:
if not hasattr(node, "uom") or node.uom in (None, ""):
# Node doesn't have a uom (Scenes for example)
return False
@ -220,7 +220,7 @@ def _check_for_states_in_uom(
possible "human readable" states. This filter passes if all of the possible
states fit inside the given filter.
"""
if not hasattr(node, "uom") or node.uom in [None, ""]:
if not hasattr(node, "uom") or node.uom in (None, ""):
# Node doesn't have a uom (Scenes for example)
return False
@ -413,7 +413,7 @@ def convert_isy_value_to_hass(
"""
if value is None or value == ISY_VALUE_UNKNOWN:
return None
if uom in [UOM_DOUBLE_TEMP, UOM_ISYV4_DEGREES]:
if uom in (UOM_DOUBLE_TEMP, UOM_ISYV4_DEGREES):
return round(float(value) / 2.0, 1)
if precision not in ("0", 0):
return round(float(value) / 10 ** int(precision), int(precision))

View file

@ -61,7 +61,7 @@ class ISYSensorEntity(ISYNodeEntity, SensorEntity):
if isy_states:
return isy_states
if uom in [UOM_ON_OFF, UOM_INDEX]:
if uom in (UOM_ON_OFF, UOM_INDEX):
return uom
return UOM_FRIENDLY_NAME.get(uom)
@ -80,7 +80,7 @@ class ISYSensorEntity(ISYNodeEntity, SensorEntity):
if isinstance(uom, dict):
return uom.get(value, value)
if uom in [UOM_INDEX, UOM_ON_OFF]:
if uom in (UOM_INDEX, UOM_ON_OFF):
return self._node.formatted
# Check if this is an index type and get formatted value
@ -101,7 +101,7 @@ class ISYSensorEntity(ISYNodeEntity, SensorEntity):
"""Get the Home Assistant unit of measurement for the device."""
raw_units = self.raw_unit_of_measurement
# Check if this is a known index pair UOM
if isinstance(raw_units, dict) or raw_units in [UOM_ON_OFF, UOM_INDEX]:
if isinstance(raw_units, dict) or raw_units in (UOM_ON_OFF, UOM_INDEX):
return None
if raw_units in (TEMP_FAHRENHEIT, TEMP_CELSIUS, UOM_DOUBLE_TEMP):
return self.hass.config.units.temperature_unit

View file

@ -79,9 +79,9 @@ def get_device_connection(
def get_resource(domain_name: str, domain_data: ConfigType) -> str:
"""Return the resource for the specified domain_data."""
if domain_name in ["switch", "light"]:
if domain_name in ("switch", "light"):
return cast(str, domain_data["output"])
if domain_name in ["binary_sensor", "sensor"]:
if domain_name in ("binary_sensor", "sensor"):
return cast(str, domain_data["source"])
if domain_name == "cover":
return cast(str, domain_data["motor"])

View file

@ -119,7 +119,7 @@ class MaxCubeClimate(ClimateEntity):
def hvac_mode(self):
"""Return current operation mode."""
mode = self._device.mode
if mode in [MAX_DEVICE_MODE_AUTOMATIC, MAX_DEVICE_MODE_BOOST]:
if mode in (MAX_DEVICE_MODE_AUTOMATIC, MAX_DEVICE_MODE_BOOST):
return HVAC_MODE_AUTO
if (
mode == MAX_DEVICE_MODE_MANUAL

View file

@ -817,7 +817,7 @@ class MediaPlayerEntity(Entity):
await self.hass.async_add_executor_job(self.toggle)
return
if self.state in [STATE_OFF, STATE_IDLE]:
if self.state in (STATE_OFF, STATE_IDLE):
await self.async_turn_on()
else:
await self.async_turn_off()

View file

@ -63,12 +63,12 @@ async def _async_reproduce_states(
# entities that are off have no other attributes to restore
return
if state.state in [
if state.state in (
STATE_ON,
STATE_PLAYING,
STATE_IDLE,
STATE_PAUSED,
]:
):
await call_service(SERVICE_TURN_ON, [])
if ATTR_MEDIA_VOLUME_LEVEL in state.attributes:

View file

@ -56,7 +56,7 @@ async def async_setup_entry(
if coordinator_alert:
entities.append(MeteoFranceAlertSensor(sensor_type, coordinator_alert))
elif sensor_type in ["rain_chance", "freeze_chance", "snow_chance"]:
elif sensor_type in ("rain_chance", "freeze_chance", "snow_chance"):
if coordinator_forecast.data.probability_forecast:
entities.append(MeteoFranceSensor(sensor_type, coordinator_forecast))
else:
@ -129,7 +129,7 @@ class MeteoFranceSensor(CoordinatorEntity, SensorEntity):
else:
value = data[path[1]]
if self._type in ["wind_speed", "wind_gust"]:
if self._type in ("wind_speed", "wind_gust"):
# convert API wind speed from m/s to km/h
value = round(value * 3.6)
return value

View file

@ -153,7 +153,7 @@ class MobileAppNotificationService(BaseNotificationService):
)
result = await response.json()
if response.status in [HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED]:
if response.status in (HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED):
log_rate_limits(self.hass, entry_data[ATTR_DEVICE_NAME], result)
continue

View file

@ -101,7 +101,7 @@ class BaseStructPlatform(BasePlatform, RestoreEntity):
def _swap_registers(self, registers):
"""Do swap as needed."""
if self._swap in [CONF_SWAP_BYTE, CONF_SWAP_WORD_BYTE]:
if self._swap in (CONF_SWAP_BYTE, CONF_SWAP_WORD_BYTE):
# convert [12][34] --> [21][43]
for i, register in enumerate(registers):
registers[i] = int.from_bytes(
@ -109,7 +109,7 @@ class BaseStructPlatform(BasePlatform, RestoreEntity):
byteorder="big",
signed=False,
)
if self._swap in [CONF_SWAP_WORD, CONF_SWAP_WORD_BYTE]:
if self._swap in (CONF_SWAP_WORD, CONF_SWAP_WORD_BYTE):
# convert [12][34] ==> [34][12]
registers.reverse()
return registers

View file

@ -114,14 +114,14 @@ class ModbusThermostat(BaseStructPlatform, RestoreEntity, ClimateEntity):
target_temperature = (
float(kwargs.get(ATTR_TEMPERATURE)) - self._offset
) / self._scale
if self._data_type in [
if self._data_type in (
DATA_TYPE_INT16,
DATA_TYPE_INT32,
DATA_TYPE_INT64,
DATA_TYPE_UINT16,
DATA_TYPE_UINT32,
DATA_TYPE_UINT64,
]:
):
target_temperature = int(target_temperature)
as_bytes = struct.pack(self._structure, target_temperature)
raw_regs = [

View file

@ -67,7 +67,7 @@ def struct_validator(config):
name = config[CONF_NAME]
structure = config.get(CONF_STRUCTURE)
swap_type = config.get(CONF_SWAP)
if data_type in [DATA_TYPE_INT, DATA_TYPE_UINT, DATA_TYPE_FLOAT]:
if data_type in (DATA_TYPE_INT, DATA_TYPE_UINT, DATA_TYPE_FLOAT):
error = f"{name} with {data_type} is not valid, trying to convert"
_LOGGER.warning(error)
try:

View file

@ -126,10 +126,10 @@ class MotionEyeMjpegCamera(MotionEyeEntity, MjpegCamera):
) -> dict[str, Any]:
"""Convert a motionEye camera to MjpegCamera internal properties."""
auth = None
if camera.get(KEY_STREAMING_AUTH_MODE) in [
if camera.get(KEY_STREAMING_AUTH_MODE) in (
HTTP_BASIC_AUTHENTICATION,
HTTP_DIGEST_AUTHENTICATION,
]:
):
auth = camera[KEY_STREAMING_AUTH_MODE]
return {

View file

@ -291,7 +291,7 @@ async def async_start( # noqa: C901
result
and result["type"] == RESULT_TYPE_ABORT
and result["reason"]
in ["already_configured", "single_instance_allowed"]
in ("already_configured", "single_instance_allowed")
):
unsub = hass.data[INTEGRATION_UNSUBSCRIBE].pop(key, None)
if unsub is None:

View file

@ -168,13 +168,13 @@ class NetatmoCamera(NetatmoBase, Camera):
return
if data["home_id"] == self._home_id and data["camera_id"] == self._id:
if data[WEBHOOK_PUSH_TYPE] in ["NACamera-off", "NACamera-disconnection"]:
if data[WEBHOOK_PUSH_TYPE] in ("NACamera-off", "NACamera-disconnection"):
self.is_streaming = False
self._status = "off"
elif data[WEBHOOK_PUSH_TYPE] in [
elif data[WEBHOOK_PUSH_TYPE] in (
"NACamera-on",
WEBHOOK_NACAMERA_CONNECTION,
]:
):
self.is_streaming = True
self._status = "on"
elif data[WEBHOOK_PUSH_TYPE] == WEBHOOK_LIGHT_MODE:

View file

@ -396,7 +396,7 @@ class NetatmoThermostat(NetatmoBase, ClimateEntity):
)
if (
preset_mode in [PRESET_BOOST, STATE_NETATMO_MAX]
preset_mode in (PRESET_BOOST, STATE_NETATMO_MAX)
and self._model == NA_VALVE
and self.hvac_mode == HVAC_MODE_HEAT
):
@ -405,7 +405,7 @@ class NetatmoThermostat(NetatmoBase, ClimateEntity):
STATE_NETATMO_HOME,
)
elif (
preset_mode in [PRESET_BOOST, STATE_NETATMO_MAX] and self._model == NA_VALVE
preset_mode in (PRESET_BOOST, STATE_NETATMO_MAX) and self._model == NA_VALVE
):
await self._home_status.async_set_room_thermpoint(
self._id,
@ -413,17 +413,17 @@ class NetatmoThermostat(NetatmoBase, ClimateEntity):
DEFAULT_MAX_TEMP,
)
elif (
preset_mode in [PRESET_BOOST, STATE_NETATMO_MAX]
preset_mode in (PRESET_BOOST, STATE_NETATMO_MAX)
and self.hvac_mode == HVAC_MODE_HEAT
):
await self._home_status.async_set_room_thermpoint(
self._id, STATE_NETATMO_HOME
)
elif preset_mode in [PRESET_BOOST, STATE_NETATMO_MAX]:
elif preset_mode in (PRESET_BOOST, STATE_NETATMO_MAX):
await self._home_status.async_set_room_thermpoint(
self._id, PRESET_MAP_NETATMO[preset_mode]
)
elif preset_mode in [PRESET_SCHEDULE, PRESET_FROST_GUARD, PRESET_AWAY]:
elif preset_mode in (PRESET_SCHEDULE, PRESET_FROST_GUARD, PRESET_AWAY):
await self._home_status.async_set_thermmode(PRESET_MAP_NETATMO[preset_mode])
else:
_LOGGER.error("Preset mode '%s' not available", preset_mode)

View file

@ -150,7 +150,7 @@ async def async_setup_entry( # noqa: C901
# The actual removal action of a Z-Wave node is reported as instance event
# Only when this event is detected we cleanup the device and entities from hass
# Note: Find a more elegant way of doing this, e.g. a notification of this event from OZW
if event in ["removenode", "removefailednode"] and "Node" in event_data:
if event in ("removenode", "removefailednode") and "Node" in event_data:
removed_nodes.append(event_data["Node"])
@callback
@ -160,9 +160,7 @@ async def async_setup_entry( # noqa: C901
node_id = value.node.node_id
# Filter out CommandClasses we're definitely not interested in.
if value.command_class in [
CommandClass.MANUFACTURER_SPECIFIC,
]:
if value.command_class in (CommandClass.MANUFACTURER_SPECIFIC,):
return
_LOGGER.debug(
@ -213,10 +211,10 @@ async def async_setup_entry( # noqa: C901
value.command_class,
)
# Handle a scene activation message
if value.command_class in [
if value.command_class in (
CommandClass.SCENE_ACTIVATION,
CommandClass.CENTRAL_SCENE,
]:
):
async_handle_scene_activated(hass, value)
return

View file

@ -88,11 +88,11 @@ class ZwaveSensorBase(ZWaveDeviceEntity, SensorEntity):
def entity_registry_enabled_default(self) -> bool:
"""Return if the entity should be enabled when first added to the entity registry."""
# We hide some of the more advanced sensors by default to not overwhelm users
if self.values.primary.command_class in [
if self.values.primary.command_class in (
CommandClass.BASIC,
CommandClass.INDICATOR,
CommandClass.NOTIFICATION,
]:
):
return False
return True

View file

@ -122,7 +122,7 @@ def _get_config_params(node, *args):
for param in raw_values:
schema = {}
if param["type"] in ["Byte", "Int", "Short"]:
if param["type"] in ("Byte", "Int", "Short"):
schema = vol.Schema(
{
vol.Required(param["label"], default=param["value"]): vol.All(

View file

@ -191,7 +191,7 @@ def browse_media( # noqa: C901
return BrowseMedia(**payload)
try:
if media_content_type in ["server", None]:
if media_content_type in ("server", None):
return server_payload(entity.plex_server)
if media_content_type == "library":

View file

@ -256,7 +256,7 @@ class PlexMediaPlayer(MediaPlayerEntity):
@property
def _is_player_active(self):
"""Report if the client is playing media."""
return self.state in [STATE_PLAYING, STATE_PAUSED]
return self.state in (STATE_PLAYING, STATE_PAUSED)
@property
def _active_media_plexapi_type(self):

View file

@ -291,10 +291,10 @@ class PlexServer:
media = self.fetch_item(rating_key)
active_session.update_media(media)
if active_session.media_content_id != rating_key and state in [
if active_session.media_content_id != rating_key and state in (
"playing",
"paused",
]:
):
await self.hass.async_add_executor_job(update_with_new_media)
async_dispatcher_send(

View file

@ -194,7 +194,7 @@ class RadarrSensor(SensorEntity):
return
if res.status_code == HTTP_OK:
if self.type in ["upcoming", "movies", "commands"]:
if self.type in ("upcoming", "movies", "commands"):
self.data = res.json()
self._state = len(self.data)
elif self.type == "diskspace":

View file

@ -357,7 +357,7 @@ class SensiboClimate(ClimateEntity):
if change_needed:
await self._async_set_ac_state_property("on", state != HVAC_MODE_OFF, True)
if state in [STATE_ON, HVAC_MODE_OFF]:
if state in (STATE_ON, HVAC_MODE_OFF):
self._external_state = None
else:
self._external_state = state

View file

@ -268,7 +268,7 @@ class SmappeeSensor(SensorEntity):
@property
def name(self):
"""Return the name for this sensor."""
if self._sensor in ["sensor", "load"]:
if self._sensor in ("sensor", "load"):
return (
f"{self._service_location.service_location_name} - "
f"{self._sensor.title()} - {self._name}"
@ -301,7 +301,7 @@ class SmappeeSensor(SensorEntity):
self,
):
"""Return the unique ID for this sensor."""
if self._sensor in ["load", "sensor"]:
if self._sensor in ("load", "sensor"):
return (
f"{self._service_location.device_serial_number}-"
f"{self._service_location.service_location_id}-"
@ -337,11 +337,11 @@ class SmappeeSensor(SensorEntity):
self._state = self._service_location.solar_power
elif self._sensor == "alwayson":
self._state = self._service_location.alwayson
elif self._sensor in [
elif self._sensor in (
"phase_voltages_a",
"phase_voltages_b",
"phase_voltages_c",
]:
):
phase_voltages = self._service_location.phase_voltages
if phase_voltages is not None:
if self._sensor == "phase_voltages_a":
@ -350,7 +350,7 @@ class SmappeeSensor(SensorEntity):
self._state = phase_voltages[1]
elif self._sensor == "phase_voltages_c":
self._state = phase_voltages[2]
elif self._sensor in ["line_voltages_a", "line_voltages_b", "line_voltages_c"]:
elif self._sensor in ("line_voltages_a", "line_voltages_b", "line_voltages_c"):
line_voltages = self._service_location.line_voltages
if line_voltages is not None:
if self._sensor == "line_voltages_a":
@ -359,14 +359,14 @@ class SmappeeSensor(SensorEntity):
self._state = line_voltages[1]
elif self._sensor == "line_voltages_c":
self._state = line_voltages[2]
elif self._sensor in [
elif self._sensor in (
"power_today",
"power_current_hour",
"power_last_5_minutes",
"solar_today",
"solar_current_hour",
"alwayson_today",
]:
):
trend_value = self._service_location.aggregated_values.get(self._sensor)
self._state = round(trend_value) if trend_value is not None else None
elif self._sensor == "load":

View file

@ -14,7 +14,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities = []
for service_location in smappee_base.smappee.service_locations.values():
for actuator_id, actuator in service_location.actuators.items():
if actuator.type in ["SWITCH", "COMFORT_PLUG"]:
if actuator.type in ("SWITCH", "COMFORT_PLUG"):
entities.append(
SmappeeActuator(
smappee_base,
@ -102,7 +102,7 @@ class SmappeeActuator(SwitchEntity):
def turn_on(self, **kwargs):
"""Turn on Comport Plug."""
if self._actuator_type in ["SWITCH", "COMFORT_PLUG"]:
if self._actuator_type in ("SWITCH", "COMFORT_PLUG"):
self._service_location.set_actuator_state(self._actuator_id, state="ON_ON")
elif self._actuator_type == "INFINITY_OUTPUT_MODULE":
self._service_location.set_actuator_state(
@ -111,7 +111,7 @@ class SmappeeActuator(SwitchEntity):
def turn_off(self, **kwargs):
"""Turn off Comport Plug."""
if self._actuator_type in ["SWITCH", "COMFORT_PLUG"]:
if self._actuator_type in ("SWITCH", "COMFORT_PLUG"):
self._service_location.set_actuator_state(
self._actuator_id, state="OFF_OFF"
)

View file

@ -165,7 +165,7 @@ class SomfyClimate(SomfyEntity, ClimateEntity):
temperature = self._climate.get_night_temperature()
elif preset_mode == PRESET_FROST_GUARD:
temperature = self._climate.get_frost_protection_temperature()
elif preset_mode in [PRESET_MANUAL, PRESET_GEOFENCING]:
elif preset_mode in (PRESET_MANUAL, PRESET_GEOFENCING):
temperature = self.target_temperature
else:
raise ValueError(f"Preset mode not supported: {preset_mode}")

View file

@ -491,7 +491,7 @@ class SpotifyMediaPlayer(MediaPlayerEntity):
)
raise NotImplementedError
if media_content_type in [None, "library"]:
if media_content_type in (None, "library"):
return await self.hass.async_add_executor_job(library_payload)
payload = {

View file

@ -180,7 +180,7 @@ class StatisticsSensor(SensorEntity):
def _add_state_to_queue(self, new_state):
"""Add the state to the queue."""
if new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]:
if new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE):
return
try:

View file

@ -414,20 +414,20 @@ def _update( # noqa: C901
err.pid,
err.name,
)
elif type_ in ["network_out", "network_in"]:
elif type_ in ("network_out", "network_in"):
counters = _net_io_counters()
if data.argument in counters:
counter = counters[data.argument][IO_COUNTER[type_]]
state = round(counter / 1024 ** 2, 1)
else:
state = None
elif type_ in ["packets_out", "packets_in"]:
elif type_ in ("packets_out", "packets_in"):
counters = _net_io_counters()
if data.argument in counters:
state = counters[data.argument][IO_COUNTER[type_]]
else:
state = None
elif type_ in ["throughput_network_out", "throughput_network_in"]:
elif type_ in ("throughput_network_out", "throughput_network_in"):
counters = _net_io_counters()
if data.argument in counters:
counter = counters[data.argument][IO_COUNTER[type_]]
@ -445,7 +445,7 @@ def _update( # noqa: C901
value = counter
else:
state = None
elif type_ in ["ipv4_address", "ipv6_address"]:
elif type_ in ("ipv4_address", "ipv6_address"):
addresses = _net_if_addrs()
if data.argument in addresses:
for addr in addresses[data.argument]:

View file

@ -465,7 +465,7 @@ class TemplateFan(TemplateEntity, FanEntity):
# Validate state
if result in _VALID_STATES:
self._state = result
elif result in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
elif result in (STATE_UNAVAILABLE, STATE_UNKNOWN):
self._state = None
else:
_LOGGER.error(
@ -529,7 +529,7 @@ class TemplateFan(TemplateEntity, FanEntity):
self._speed = speed
self._percentage = self.speed_to_percentage(speed)
self._preset_mode = speed if speed in self.preset_modes else None
elif speed in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
elif speed in (STATE_UNAVAILABLE, STATE_UNKNOWN):
self._speed = None
self._percentage = 0
self._preset_mode = None
@ -573,7 +573,7 @@ class TemplateFan(TemplateEntity, FanEntity):
self._speed = preset_mode
self._percentage = None
self._preset_mode = preset_mode
elif preset_mode in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
elif preset_mode in (STATE_UNAVAILABLE, STATE_UNKNOWN):
self._speed = None
self._percentage = None
self._preset_mode = None
@ -594,7 +594,7 @@ class TemplateFan(TemplateEntity, FanEntity):
self._oscillating = True
elif oscillating == "False" or oscillating is False:
self._oscillating = False
elif oscillating in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
elif oscillating in (STATE_UNAVAILABLE, STATE_UNKNOWN):
self._oscillating = None
else:
_LOGGER.error(
@ -608,7 +608,7 @@ class TemplateFan(TemplateEntity, FanEntity):
# Validate direction
if direction in _VALID_DIRECTIONS:
self._direction = direction
elif direction in [STATE_UNAVAILABLE, STATE_UNKNOWN]:
elif direction in (STATE_UNAVAILABLE, STATE_UNKNOWN):
self._direction = None
else:
_LOGGER.error(

View file

@ -44,7 +44,7 @@ class TeslaSensor(TeslaDevice, SensorEntity):
if self.type == "outside":
return self.tesla_device.get_outside_temp()
return self.tesla_device.get_inside_temp()
if self.tesla_device.type in ["range sensor", "mileage sensor"]:
if self.tesla_device.type in ("range sensor", "mileage sensor"):
units = self.tesla_device.measurement
if units == "LENGTH_MILES":
return self.tesla_device.get_value()

View file

@ -160,7 +160,7 @@ class ThermoworksSmokeSensor(SensorEntity):
}
# set extended attributes for main probe sensors
if self.type in [PROBE_1, PROBE_2]:
if self.type in (PROBE_1, PROBE_2):
for key, val in values.items():
# add all attributes that don't contain any probe name
# or contain a matching probe name

View file

@ -286,7 +286,7 @@ class UpCloudServerEntity(CoordinatorEntity):
"""Return True if entity is available."""
return super().available and STATE_MAP.get(
self._server.state, self._server.state
) in [STATE_ON, STATE_OFF]
) in (STATE_ON, STATE_OFF)
@property
def extra_state_attributes(self) -> dict[str, Any]:

View file

@ -131,7 +131,7 @@ class UnifiVideoCamera(Camera):
return self._caminfo["recordingSettings"][
"fullTimeRecordEnabled"
] or recording_state in ["MOTION_INPROGRESS", "MOTION_FINISHED"]
] or recording_state in ("MOTION_INPROGRESS", "MOTION_FINISHED")
@property
def motion_detection_enabled(self):

View file

@ -32,7 +32,7 @@ RESULT_INVALID_AUTH = "invalid_auth"
def host_valid(host):
"""Return True if hostname or IP address is valid."""
try:
if ipaddress.ip_address(host).version in [4, 6]:
if ipaddress.ip_address(host).version in (4, 6):
return True
except ValueError:
disallowed = re.compile(r"[^a-zA-Z\d\-]")

View file

@ -87,7 +87,7 @@ async def async_setup_entry(
(
key
for key in config_entry.data.get(CONF_APPS, {})
if key in [CONF_INCLUDE, CONF_EXCLUDE]
if key in (CONF_INCLUDE, CONF_EXCLUDE)
),
None,
)

View file

@ -73,9 +73,9 @@ def _item_to_children_media_class(item, info=None):
def _item_to_media_class(item, parent_item=None):
if "type" not in item:
return MEDIA_CLASS_DIRECTORY
if item["type"] in ["webradio", "mywebradio"]:
if item["type"] in ("webradio", "mywebradio"):
return MEDIA_CLASS_CHANNEL
if item["type"] in ["song", "cuesong"]:
if item["type"] in ("song", "cuesong"):
return MEDIA_CLASS_TRACK
if item.get("artist"):
return MEDIA_CLASS_ALBUM

View file

@ -259,7 +259,7 @@ class Volumio(MediaPlayerEntity):
async def async_browse_media(self, media_content_type=None, media_content_id=None):
"""Implement the websocket media browsing helper."""
self.thumbnail_cache = {}
if media_content_type in [None, "library"]:
if media_content_type in (None, "library"):
return await browse_top_level(self._volumio)
return await browse_node(

View file

@ -45,7 +45,7 @@ async def build_item_response(
"""Create response payload for the provided media query."""
apps: InstalledPackagesList = await client.smartglass.get_installed_apps(device_id)
if media_content_type in [None, "library"]:
if media_content_type in (None, "library"):
library_info = BrowseMedia(
media_class=MEDIA_CLASS_DIRECTORY,
media_content_id="library",

View file

@ -32,23 +32,23 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
gateway = hass.data[DOMAIN][GATEWAYS_KEY][config_entry.entry_id]
for entity in gateway.devices["binary_sensor"]:
model = entity["model"]
if model in ["motion", "sensor_motion", "sensor_motion.aq2"]:
if model in ("motion", "sensor_motion", "sensor_motion.aq2"):
entities.append(XiaomiMotionSensor(entity, hass, gateway, config_entry))
elif model in ["magnet", "sensor_magnet", "sensor_magnet.aq2"]:
elif model in ("magnet", "sensor_magnet", "sensor_magnet.aq2"):
entities.append(XiaomiDoorSensor(entity, gateway, config_entry))
elif model == "sensor_wleak.aq1":
entities.append(XiaomiWaterLeakSensor(entity, gateway, config_entry))
elif model in ["smoke", "sensor_smoke"]:
elif model in ("smoke", "sensor_smoke"):
entities.append(XiaomiSmokeSensor(entity, gateway, config_entry))
elif model in ["natgas", "sensor_natgas"]:
elif model in ("natgas", "sensor_natgas"):
entities.append(XiaomiNatgasSensor(entity, gateway, config_entry))
elif model in [
elif model in (
"switch",
"sensor_switch",
"sensor_switch.aq2",
"sensor_switch.aq3",
"remote.b1acn01",
]:
):
if "proto" not in entity or int(entity["proto"][0:1]) == 1:
data_key = "status"
else:
@ -56,13 +56,13 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities.append(
XiaomiButton(entity, "Switch", data_key, hass, gateway, config_entry)
)
elif model in [
elif model in (
"86sw1",
"sensor_86sw1",
"sensor_86sw1.aq1",
"remote.b186acn01",
"remote.b186acn02",
]:
):
if "proto" not in entity or int(entity["proto"][0:1]) == 1:
data_key = "channel_0"
else:
@ -72,13 +72,13 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entity, "Wall Switch", data_key, hass, gateway, config_entry
)
)
elif model in [
elif model in (
"86sw2",
"sensor_86sw2",
"sensor_86sw2.aq1",
"remote.b286acn01",
"remote.b286acn02",
]:
):
if "proto" not in entity or int(entity["proto"][0:1]) == 1:
data_key_left = "channel_0"
data_key_right = "channel_1"
@ -115,9 +115,9 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
config_entry,
)
)
elif model in ["cube", "sensor_cube", "sensor_cube.aqgl01"]:
elif model in ("cube", "sensor_cube", "sensor_cube.aqgl01"):
entities.append(XiaomiCube(entity, hass, gateway, config_entry))
elif model in ["vibration", "vibration.aq1"]:
elif model in ("vibration", "vibration.aq1"):
entities.append(
XiaomiVibration(entity, "Vibration", "status", gateway, config_entry)
)

View file

@ -16,7 +16,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
gateway = hass.data[DOMAIN][GATEWAYS_KEY][config_entry.entry_id]
for device in gateway.devices["cover"]:
model = device["model"]
if model in ["curtain", "curtain.aq2", "curtain.hagl04"]:
if model in ("curtain", "curtain.aq2", "curtain.hagl04"):
if "proto" not in device or int(device["proto"][0:1]) == 1:
data_key = DATA_KEY_PROTO_V1
else:

View file

@ -24,7 +24,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
gateway = hass.data[DOMAIN][GATEWAYS_KEY][config_entry.entry_id]
for device in gateway.devices["light"]:
model = device["model"]
if model in ["gateway", "gateway.v3"]:
if model in ("gateway", "gateway.v3"):
entities.append(
XiaomiGatewayLight(device, "Gateway Light", gateway, config_entry)
)

View file

@ -47,7 +47,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities.append(
XiaomiSensor(device, "Humidity", "humidity", gateway, config_entry)
)
elif device["model"] in ["weather", "weather.v1"]:
elif device["model"] in ("weather", "weather.v1"):
entities.append(
XiaomiSensor(
device, "Temperature", "temperature", gateway, config_entry
@ -63,13 +63,13 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities.append(
XiaomiSensor(device, "Illumination", "lux", gateway, config_entry)
)
elif device["model"] in ["gateway", "gateway.v3", "acpartner.v3"]:
elif device["model"] in ("gateway", "gateway.v3", "acpartner.v3"):
entities.append(
XiaomiSensor(
device, "Illumination", "illumination", gateway, config_entry
)
)
elif device["model"] in ["vibration"]:
elif device["model"] in ("vibration",):
entities.append(
XiaomiSensor(
device, "Bed Activity", "bed_activity", gateway, config_entry
@ -151,13 +151,13 @@ class XiaomiSensor(XiaomiDevice, SensorEntity):
value = data.get(self._data_key)
if value is None:
return False
if self._data_key in ["coordination", "status"]:
if self._data_key in ("coordination", "status"):
self._state = value
return True
value = float(value)
if self._data_key in ["temperature", "humidity", "pressure"]:
if self._data_key in ("temperature", "humidity", "pressure"):
value /= 100
elif self._data_key in ["illumination"]:
elif self._data_key in ("illumination",):
value = max(value - 300, 0)
if self._data_key == "temperature" and (value < -50 or value > 60):
return False
@ -165,7 +165,7 @@ class XiaomiSensor(XiaomiDevice, SensorEntity):
return False
if self._data_key == "pressure" and value == 0:
return False
if self._data_key in ["illumination", "lux"]:
if self._data_key in ("illumination", "lux"):
self._state = round(value)
else:
self._state = round(value, 1)

View file

@ -37,34 +37,34 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
device, "Plug", data_key, True, gateway, config_entry
)
)
elif model in [
elif model in (
"ctrl_neutral1",
"ctrl_neutral1.aq1",
"switch_b1lacn02",
"switch.b1lacn02",
]:
):
entities.append(
XiaomiGenericSwitch(
device, "Wall Switch", "channel_0", False, gateway, config_entry
)
)
elif model in [
elif model in (
"ctrl_ln1",
"ctrl_ln1.aq1",
"switch_b1nacn02",
"switch.b1nacn02",
]:
):
entities.append(
XiaomiGenericSwitch(
device, "Wall Switch LN", "channel_0", False, gateway, config_entry
)
)
elif model in [
elif model in (
"ctrl_neutral2",
"ctrl_neutral2.aq1",
"switch_b2lacn02",
"switch.b2lacn02",
]:
):
entities.append(
XiaomiGenericSwitch(
device,
@ -85,12 +85,12 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
config_entry,
)
)
elif model in [
elif model in (
"ctrl_ln2",
"ctrl_ln2.aq1",
"switch_b2nacn02",
"switch.b2nacn02",
]:
):
entities.append(
XiaomiGenericSwitch(
device,
@ -111,7 +111,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
config_entry,
)
)
elif model in ["86plug", "ctrl_86plug", "ctrl_86plug.aq1"]:
elif model in ("86plug", "ctrl_86plug", "ctrl_86plug.aq1"):
if "proto" not in device or int(device["proto"][0:1]) == 1:
data_key = "status"
else: