Improve lists in integrations [T-U] (#113243)

pull/112833/head^2
Joost Lekkerkerker 2024-03-13 17:54:46 +01:00 committed by GitHub
parent cdba14acd4
commit 96cebdf096
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 153 additions and 175 deletions

View File

@ -69,17 +69,14 @@ async def async_setup_entry(
api: Tami4EdgeAPI = data[API]
coordinator: Tami4EdgeWaterQualityCoordinator = data[COORDINATOR]
entities = []
for entity_description in ENTITY_DESCRIPTIONS:
entities.append(
Tami4EdgeSensorEntity(
coordinator=coordinator,
api=api,
entity_description=entity_description,
)
async_add_entities(
Tami4EdgeSensorEntity(
coordinator=coordinator,
api=api,
entity_description=entity_description,
)
async_add_entities(entities)
for entity_description in ENTITY_DESCRIPTIONS
)
class Tami4EdgeSensorEntity(

View File

@ -78,12 +78,11 @@ def setup_platform(
# Get MUT information to create the sensors.
gateway.update()
entities = []
for mtu in gateway.data:
for description in SENSORS:
entities.append(Ted5000Sensor(gateway, name, mtu, description))
add_entities(entities)
add_entities(
Ted5000Sensor(gateway, name, mtu, description)
for mtu in gateway.data
for description in SENSORS
)
class Ted5000Sensor(SensorEntity):

View File

@ -186,8 +186,9 @@ class TelldusLiveClient:
self._hass.data[CONFIG_ENTRY_IS_SETUP].add(component)
device_ids = []
if device.is_sensor:
for item in device.items:
device_ids.append((device.device_id, item.name, item.scale))
device_ids.extend(
(device.device_id, item.name, item.scale) for item in device.items
)
else:
device_ids.append(device_id)
for _id in device_ids:

View File

@ -196,20 +196,16 @@ def setup_platform(
labels, use_display_name=True
)
entities = []
for camera in config[CONF_SOURCE]:
entities.append(
TensorFlowImageProcessor(
hass,
camera[CONF_ENTITY_ID],
camera.get(CONF_NAME),
category_index,
config,
)
add_entities(
TensorFlowImageProcessor(
hass,
camera[CONF_ENTITY_ID],
camera.get(CONF_NAME),
category_index,
config,
)
add_entities(entities)
for camera in config[CONF_SOURCE]
)
class TensorFlowImageProcessor(ImageProcessingEntity):

View File

@ -86,22 +86,21 @@ def setup_platform(
try:
mgr = thermoworks_smoke.initialize_app(email, password, True, excluded)
# list of sensor devices
dev = []
# get list of registered devices
for serial in mgr.serials():
for variable in monitored_variables:
dev.append(ThermoworksSmokeSensor(variable, serial, mgr))
add_entities(dev, True)
except HTTPError as error:
msg = f"{error.strerror}"
if "EMAIL_NOT_FOUND" in msg or "INVALID_PASSWORD" in msg:
_LOGGER.error("Invalid email and password combination")
else:
_LOGGER.error(msg)
else:
add_entities(
(
ThermoworksSmokeSensor(variable, serial, mgr)
for serial in mgr.serials()
for variable in monitored_variables
),
True,
)
class ThermoworksSmokeSensor(SensorEntity):

View File

@ -166,23 +166,22 @@ async def ws_list_datasets(
"""Get a list of thread datasets."""
store = await dataset_store.async_get_store(hass)
result = []
preferred_dataset = store.preferred_dataset
for dataset in store.datasets.values():
result.append(
{
"channel": dataset.channel,
"created": dataset.created,
"dataset_id": dataset.id,
"extended_pan_id": dataset.extended_pan_id,
"network_name": dataset.network_name,
"pan_id": dataset.pan_id,
"preferred": dataset.id == preferred_dataset,
"preferred_border_agent_id": dataset.preferred_border_agent_id,
"preferred_extended_address": dataset.preferred_extended_address,
"source": dataset.source,
}
)
result = [
{
"channel": dataset.channel,
"created": dataset.created,
"dataset_id": dataset.id,
"extended_pan_id": dataset.extended_pan_id,
"network_name": dataset.network_name,
"pan_id": dataset.pan_id,
"preferred": dataset.id == preferred_dataset,
"preferred_border_agent_id": dataset.preferred_border_agent_id,
"preferred_extended_address": dataset.preferred_extended_address,
"source": dataset.source,
}
for dataset in store.datasets.values()
]
connection.send_result(msg["id"], {"datasets": result})

View File

@ -18,11 +18,8 @@ async def async_get_config_entry_diagnostics(
"""Return diagnostics for a config entry."""
tibber_connection: tibber.Tibber = hass.data[DOMAIN]
diagnostics_data = {}
homes = []
for home in tibber_connection.get_homes(only_active=False):
homes.append(
return {
"homes": [
{
"last_data_timestamp": home.last_data_timestamp,
"has_active_subscription": home.has_active_subscription,
@ -30,7 +27,6 @@ async def async_get_config_entry_diagnostics(
"last_cons_data_timestamp": home.last_cons_data_timestamp,
"country": home.country,
}
)
diagnostics_data["homes"] = homes
return diagnostics_data
for home in tibber_connection.get_homes(only_active=False)
]
}

View File

@ -295,8 +295,10 @@ async def async_setup_entry(
entities.append(TibberSensorElPrice(home))
if coordinator is None:
coordinator = TibberDataCoordinator(hass, tibber_connection)
for entity_description in SENSORS:
entities.append(TibberDataSensor(home, coordinator, entity_description))
entities.extend(
TibberDataSensor(home, coordinator, entity_description)
for entity_description in SENSORS
)
if home.has_real_time_consumption:
await home.rt_subscribe(

View File

@ -36,21 +36,21 @@ async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up TotalConnect alarm panels based on a config entry."""
alarms = []
alarms: list[TotalConnectAlarm] = []
coordinator: TotalConnectDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
for location_id, location in coordinator.client.locations.items():
location_name = location.location_name
for partition_id in location.partitions:
alarms.append(
TotalConnectAlarm(
coordinator=coordinator,
name=location_name,
location_id=location_id,
partition_id=partition_id,
)
alarms.extend(
TotalConnectAlarm(
coordinator=coordinator,
name=location_name,
location_id=location_id,
partition_id=partition_id,
)
for partition_id in location.partitions
)
async_add_entities(alarms)

View File

@ -55,10 +55,13 @@ def setup_platform(
host = config[CONF_HOST]
py_touchline = PyTouchline()
number_of_devices = int(py_touchline.get_number_of_devices(host))
devices = []
for device_id in range(0, number_of_devices):
devices.append(Touchline(PyTouchline(device_id)))
add_entities(devices, True)
add_entities(
(
Touchline(PyTouchline(device_id))
for device_id in range(0, number_of_devices)
),
True,
)
class Touchline(ClimateEntity):

View File

@ -37,8 +37,10 @@ async def async_setup_entry(
if device.is_strip:
# Historically we only add the children if the device is a strip
_LOGGER.debug("Initializing strip with %s sockets", len(device.children))
for child in device.children:
entities.append(SmartPlugSwitchChild(device, parent_coordinator, child))
entities.extend(
SmartPlugSwitchChild(device, parent_coordinator, child)
for child in device.children
)
elif device.is_plug:
entities.append(SmartPlugSwitch(device, parent_coordinator))

View File

@ -111,13 +111,9 @@ async def async_list_contexts(
def _get_debug_traces(hass: HomeAssistant, key: str) -> list[dict[str, Any]]:
"""Return a serializable list of debug traces for a script or automation."""
traces: list[dict[str, Any]] = []
if traces_for_key := _get_data(hass).get(key):
for trace in traces_for_key.values():
traces.append(trace.as_short_dict())
return traces
return [trace.as_short_dict() for trace in traces_for_key.values()]
return []
async def async_list_traces(

View File

@ -26,9 +26,10 @@ async def async_get_config_entry_diagnostics(
),
)
device_data: list = []
for coordinator in coordinator_data[COORDINATOR_LIST]:
device_data.append(coordinator.device.device_info.model_number)
device_data: list = [
coordinator.device.device_info.model_number
for coordinator in coordinator_data[COORDINATOR_LIST]
]
return {
"gateway_version": device.sw_version,

View File

@ -71,11 +71,11 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := ALARM.get(device.category):
for description in descriptions:
if description.key in device.status:
entities.append(
TuyaAlarmEntity(device, hass_data.manager, description)
)
entities.extend(
TuyaAlarmEntity(device, hass_data.manager, description)
for description in descriptions
if description.key in device.status
)
async_add_entities(entities)
async_discover_device([*hass_data.manager.device_map])

View File

@ -71,11 +71,11 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := BUTTONS.get(device.category):
for description in descriptions:
if description.key in device.status:
entities.append(
TuyaButtonEntity(device, hass_data.manager, description)
)
entities.extend(
TuyaButtonEntity(device, hass_data.manager, description)
for description in descriptions
if description.key in device.status
)
async_add_entities(entities)

View File

@ -155,14 +155,14 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := COVERS.get(device.category):
for description in descriptions:
entities.extend(
TuyaCoverEntity(device, hass_data.manager, description)
for description in descriptions
if (
description.key in device.function
or description.key in device.status_range
):
entities.append(
TuyaCoverEntity(device, hass_data.manager, description)
)
)
)
async_add_entities(entities)

View File

@ -417,11 +417,11 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := LIGHTS.get(device.category):
for description in descriptions:
if description.key in device.status:
entities.append(
TuyaLightEntity(device, hass_data.manager, description)
)
entities.extend(
TuyaLightEntity(device, hass_data.manager, description)
for description in descriptions
if description.key in device.status
)
async_add_entities(entities)

View File

@ -294,11 +294,11 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := NUMBERS.get(device.category):
for description in descriptions:
if description.key in device.status:
entities.append(
TuyaNumberEntity(device, hass_data.manager, description)
)
entities.extend(
TuyaNumberEntity(device, hass_data.manager, description)
for description in descriptions
if description.key in device.status
)
async_add_entities(entities)

View File

@ -332,11 +332,11 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := SELECTS.get(device.category):
for description in descriptions:
if description.key in device.status:
entities.append(
TuyaSelectEntity(device, hass_data.manager, description)
)
entities.extend(
TuyaSelectEntity(device, hass_data.manager, description)
for description in descriptions
if description.key in device.status
)
async_add_entities(entities)

View File

@ -1087,11 +1087,11 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := SENSORS.get(device.category):
for description in descriptions:
if description.key in device.status:
entities.append(
TuyaSensorEntity(device, hass_data.manager, description)
)
entities.extend(
TuyaSensorEntity(device, hass_data.manager, description)
for description in descriptions
if description.key in device.status
)
async_add_entities(entities)

View File

@ -672,11 +672,11 @@ async def async_setup_entry(
for device_id in device_ids:
device = hass_data.manager.device_map[device_id]
if descriptions := SWITCHES.get(device.category):
for description in descriptions:
if description.key in device.status:
entities.append(
TuyaSwitchEntity(device, hass_data.manager, description)
)
entities.extend(
TuyaSwitchEntity(device, hass_data.manager, description)
for description in descriptions
if description.key in device.status
)
async_add_entities(entities)

View File

@ -130,10 +130,7 @@ class TwinklyLight(LightEntity):
@property
def effect_list(self) -> list[str]:
"""Return the list of saved effects."""
effect_list = []
for movie in self._movies:
effect_list.append(f"{movie['id']} {movie['name']}")
return effect_list
return [f"{movie['id']} {movie['name']}" for movie in self._movies]
async def async_added_to_hass(self) -> None:
"""Device is added to hass."""

View File

@ -133,17 +133,5 @@ def _find(regions, region_id):
def _make_regions_object(regions):
regions_list = []
for region in regions:
regions_list.append(
{
"id": region["regionId"],
"name": region["regionName"],
}
)
regions_list = sorted(regions_list, key=lambda region: region["name"].lower())
regions_object = {}
for region in regions_list:
regions_object[region["id"]] = region["name"]
return regions_object
regions = sorted(regions, key=lambda region: region["regionName"].lower())
return {region["regionId"]: region["regionName"] for region in regions}

View File

@ -83,14 +83,14 @@ class UnifiEntityLoader:
Provide inactive clients to device tracker and switch platform.
"""
config = self.hub.config
macs: list[str] = []
entity_registry = er.async_get(self.hub.hass)
for entry in async_entries_for_config_entry(
entity_registry, config.entry.entry_id
):
if entry.domain == Platform.DEVICE_TRACKER and "-" in entry.unique_id:
macs.append(entry.unique_id.split("-", 1)[1])
macs: list[str] = [
entry.unique_id.split("-", 1)[1]
for entry in async_entries_for_config_entry(
entity_registry, config.entry.entry_id
)
if entry.domain == Platform.DEVICE_TRACKER and "-" in entry.unique_id
]
api = self.hub.api
for mac in config.option_supported_clients + config.option_block_clients + macs:
if mac not in api.clients and mac in api.clients_all:

View File

@ -45,12 +45,11 @@ async def async_setup_entry(
async_dispatcher_connect(hass, _ufpd(entry, DISPATCH_ADOPT), _add_new_device)
)
entities = []
for device in data.get_by_types({ModelType.LIGHT}):
if device.can_write(data.api.bootstrap.auth_user):
entities.append(ProtectLight(data, device))
async_add_entities(entities)
async_add_entities(
ProtectLight(data, device)
for device in data.get_by_types({ModelType.LIGHT})
if device.can_write(data.api.bootstrap.auth_user)
)
def unifi_brightness_to_hass(value: int) -> int:

View File

@ -130,8 +130,10 @@ def _get_doorbell_options(api: ProtectApiClient) -> list[dict[str, Any]]:
def _get_paired_camera_options(api: ProtectApiClient) -> list[dict[str, Any]]:
options = [{"id": TYPE_EMPTY_VALUE, "name": "Not Paired"}]
for camera in api.bootstrap.cameras.values():
options.append({"id": camera.id, "name": camera.display_name or camera.type})
options.extend(
{"id": camera.id, "name": camera.display_name or camera.type}
for camera in api.bootstrap.cameras.values()
)
return options

View File

@ -52,10 +52,11 @@ async def test_migrate_reboot_button(
assert ufp.api.update.called
assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac
buttons = []
for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id):
if entity.domain == Platform.BUTTON.value:
buttons.append(entity)
buttons = [
entity
for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id)
if entity.domain == Platform.BUTTON.value
]
assert len(buttons) == 4
assert registry.async_get(f"{Platform.BUTTON}.test_light_1_reboot_device") is None
@ -133,10 +134,11 @@ async def test_migrate_reboot_button_no_device(
assert ufp.api.update.called
assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac
buttons = []
for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id):
if entity.domain == Platform.BUTTON.value:
buttons.append(entity)
buttons = [
entity
for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id)
if entity.domain == Platform.BUTTON.value
]
assert len(buttons) == 3
entity = registry.async_get(f"{Platform.BUTTON}.unifiprotect_{light2_id.lower()}")

View File

@ -365,8 +365,7 @@ async def test_platform_setup(hass: HomeAssistant) -> None:
def add_entities(new_entities):
"""Add devices to list."""
for dev in new_entities:
entities.append(dev)
entities.extend(new_entities)
setup_ok = True
try: