Enable Ruff RET504 (#114528)

* Enable Ruff RET504

* fix test

* Use noqa instead of cast

* fix sonos RET504

---------

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Sid 2024-04-06 11:07:37 +02:00 committed by GitHub
parent a28731c294
commit 0d66d298ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
200 changed files with 252 additions and 595 deletions

View File

@ -146,9 +146,7 @@ def get_arguments() -> argparse.Namespace:
help="Skips validation of operating system", help="Skips validation of operating system",
) )
arguments = parser.parse_args() return parser.parse_args()
return arguments
def check_threads() -> None: def check_threads() -> None:

View File

@ -23,9 +23,7 @@ async def async_get_config_entry_diagnostics(
config_entry.entry_id config_entry.entry_id
] ]
diagnostics_data = { return {
"config_entry_data": async_redact_data(dict(config_entry.data), TO_REDACT), "config_entry_data": async_redact_data(dict(config_entry.data), TO_REDACT),
"coordinator_data": coordinator.data, "coordinator_data": coordinator.data,
} }
return diagnostics_data

View File

@ -26,9 +26,7 @@ async def async_get_config_entry_diagnostics(
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
coordinator: AirlyDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id] coordinator: AirlyDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
diagnostics_data = { return {
"config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT), "config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT),
"coordinator_data": coordinator.data, "coordinator_data": coordinator.data,
} }
return diagnostics_data

View File

@ -23,8 +23,6 @@ async def async_get_config_entry_diagnostics(
acc: AladdinConnectClient = hass.data[DOMAIN][config_entry.entry_id] acc: AladdinConnectClient = hass.data[DOMAIN][config_entry.entry_id]
diagnostics_data = { return {
"doors": async_redact_data(acc.doors, TO_REDACT), "doors": async_redact_data(acc.doors, TO_REDACT),
} }
return diagnostics_data

View File

@ -1764,10 +1764,7 @@ class AlexaRangeController(AlexaCapability):
speed_list = self.entity.attributes.get(vacuum.ATTR_FAN_SPEED_LIST) speed_list = self.entity.attributes.get(vacuum.ATTR_FAN_SPEED_LIST)
speed = self.entity.attributes.get(vacuum.ATTR_FAN_SPEED) speed = self.entity.attributes.get(vacuum.ATTR_FAN_SPEED)
if speed_list is not None and speed is not None: if speed_list is not None and speed is not None:
speed_index = next( return next((i for i, v in enumerate(speed_list) if v == speed), None)
(i for i, v in enumerate(speed_list) if v == speed), None
)
return speed_index
# Valve Position # Valve Position
if self.instance == f"{valve.DOMAIN}.{valve.ATTR_POSITION}": if self.instance == f"{valve.DOMAIN}.{valve.ATTR_POSITION}":

View File

@ -203,8 +203,7 @@ class AmcrestChecker(ApiWrapper):
async def async_command(self, *args: Any, **kwargs: Any) -> httpx.Response: async def async_command(self, *args: Any, **kwargs: Any) -> httpx.Response:
"""amcrest.ApiWrapper.command wrapper to catch errors.""" """amcrest.ApiWrapper.command wrapper to catch errors."""
async with self._async_command_wrapper(): async with self._async_command_wrapper():
ret = await super().async_command(*args, **kwargs) return await super().async_command(*args, **kwargs)
return ret
@asynccontextmanager @asynccontextmanager
async def async_stream_command( async def async_stream_command(

View File

@ -107,9 +107,7 @@ class AprilaireClimate(BaseAprilaireEntity, ClimateEntity):
features = features | ClimateEntityFeature.PRESET_MODE features = features | ClimateEntityFeature.PRESET_MODE
features = features | ClimateEntityFeature.FAN_MODE return features | ClimateEntityFeature.FAN_MODE
return features
@property @property
def current_humidity(self) -> int | None: def current_humidity(self) -> int | None:

View File

@ -257,7 +257,7 @@ class ArcamFmj(MediaPlayerEntity):
for preset in presets.values() for preset in presets.values()
] ]
root = BrowseMedia( return BrowseMedia(
title="Arcam FMJ Receiver", title="Arcam FMJ Receiver",
media_class=MediaClass.DIRECTORY, media_class=MediaClass.DIRECTORY,
media_content_id="root", media_content_id="root",
@ -267,8 +267,6 @@ class ArcamFmj(MediaPlayerEntity):
children=radio, children=radio,
) )
return root
@convert_exception @convert_exception
async def async_play_media( async def async_play_media(
self, media_type: MediaType | str, media_id: str, **kwargs: Any self, media_type: MediaType | str, media_id: str, **kwargs: Any

View File

@ -49,11 +49,10 @@ class ArrisDeviceScanner(DeviceScanner):
def get_device_name(self, device: str) -> str | None: def get_device_name(self, device: str) -> str | None:
"""Return the name of the given device or None if we don't know.""" """Return the name of the given device or None if we don't know."""
name = next( return next(
(result.hostname for result in self.last_results if result.mac == device), (result.hostname for result in self.last_results if result.mac == device),
None, None,
) )
return name
def _update_info(self) -> None: def _update_info(self) -> None:
"""Ensure the information from the Arris TG2492LG router is up to date.""" """Ensure the information from the Arris TG2492LG router is up to date."""

View File

@ -254,7 +254,7 @@ class AsusWrtLegacyBridge(AsusWrtBridge):
async def async_get_available_sensors(self) -> dict[str, dict[str, Any]]: async def async_get_available_sensors(self) -> dict[str, dict[str, Any]]:
"""Return a dictionary of available sensors for this bridge.""" """Return a dictionary of available sensors for this bridge."""
sensors_temperatures = await self._get_available_temperature_sensors() sensors_temperatures = await self._get_available_temperature_sensors()
sensors_types = { return {
SENSORS_TYPE_BYTES: { SENSORS_TYPE_BYTES: {
KEY_SENSORS: SENSORS_BYTES, KEY_SENSORS: SENSORS_BYTES,
KEY_METHOD: self._get_bytes, KEY_METHOD: self._get_bytes,
@ -272,7 +272,6 @@ class AsusWrtLegacyBridge(AsusWrtBridge):
KEY_METHOD: self._get_temperatures, KEY_METHOD: self._get_temperatures,
}, },
} }
return sensors_types
async def _get_available_temperature_sensors(self) -> list[str]: async def _get_available_temperature_sensors(self) -> list[str]:
"""Check which temperature information is available on the router.""" """Check which temperature information is available on the router."""
@ -351,7 +350,7 @@ class AsusWrtHttpBridge(AsusWrtBridge):
"""Return a dictionary of available sensors for this bridge.""" """Return a dictionary of available sensors for this bridge."""
sensors_temperatures = await self._get_available_temperature_sensors() sensors_temperatures = await self._get_available_temperature_sensors()
sensors_loadavg = await self._get_loadavg_sensors_availability() sensors_loadavg = await self._get_loadavg_sensors_availability()
sensors_types = { return {
SENSORS_TYPE_BYTES: { SENSORS_TYPE_BYTES: {
KEY_SENSORS: SENSORS_BYTES, KEY_SENSORS: SENSORS_BYTES,
KEY_METHOD: self._get_bytes, KEY_METHOD: self._get_bytes,
@ -369,7 +368,6 @@ class AsusWrtHttpBridge(AsusWrtBridge):
KEY_METHOD: self._get_temperatures, KEY_METHOD: self._get_temperatures,
}, },
} }
return sensors_types
async def _get_available_temperature_sensors(self) -> list[str]: async def _get_available_temperature_sensors(self) -> list[str]:
"""Check which temperature information is available on the router.""" """Check which temperature information is available on the router."""

View File

@ -147,8 +147,7 @@ def _prepare_result_json(
) -> data_entry_flow.FlowResult: ) -> data_entry_flow.FlowResult:
"""Convert result to JSON.""" """Convert result to JSON."""
if result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY: if result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY:
data = result.copy() return result.copy()
return data
if result["type"] != data_entry_flow.FlowResultType.FORM: if result["type"] != data_entry_flow.FlowResultType.FORM:
return result return result

View File

@ -863,8 +863,6 @@ class BluesoundPlayer(MediaPlayerEntity):
if self._group_name is None: if self._group_name is None:
return None return None
bluesound_group = []
device_group = self._group_name.split("+") device_group = self._group_name.split("+")
sorted_entities = sorted( sorted_entities = sorted(
@ -872,14 +870,12 @@ class BluesoundPlayer(MediaPlayerEntity):
key=lambda entity: entity.is_master, key=lambda entity: entity.is_master,
reverse=True, reverse=True,
) )
bluesound_group = [ return [
entity.name entity.name
for entity in sorted_entities for entity in sorted_entities
if entity.bluesound_device_name in device_group if entity.bluesound_device_name in device_group
] ]
return bluesound_group
async def async_unjoin(self): async def async_unjoin(self):
"""Unjoin the player from a group.""" """Unjoin the player from a group."""
if self._master is None: if self._master is None:

View File

@ -21,9 +21,7 @@ async def async_get_config_entry_diagnostics(
device_info = await coordinator.client.get_system_info() device_info = await coordinator.client.get_system_info()
diagnostics_data = { return {
"config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT), "config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT),
"device_info": async_redact_data(device_info, TO_REDACT), "device_info": async_redact_data(device_info, TO_REDACT),
} }
return diagnostics_data

View File

@ -20,11 +20,9 @@ async def async_get_config_entry_diagnostics(
config_entry.entry_id config_entry.entry_id
] ]
diagnostics_data = { return {
"info": dict(config_entry.data), "info": dict(config_entry.data),
"data": asdict(coordinator.data), "data": asdict(coordinator.data),
"model": coordinator.brother.model, "model": coordinator.brother.model,
"firmware": coordinator.brother.firmware, "firmware": coordinator.brother.firmware,
} }
return diagnostics_data

View File

@ -140,10 +140,8 @@ async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> Non
def _get_canary_api_instance(entry: ConfigEntry) -> Api: def _get_canary_api_instance(entry: ConfigEntry) -> Api:
"""Initialize a new instance of CanaryApi.""" """Initialize a new instance of CanaryApi."""
canary = Api( return Api(
entry.data[CONF_USERNAME], entry.data[CONF_USERNAME],
entry.data[CONF_PASSWORD], entry.data[CONF_PASSWORD],
entry.options.get(CONF_TIMEOUT, DEFAULT_TIMEOUT), entry.options.get(CONF_TIMEOUT, DEFAULT_TIMEOUT),
) )
return canary

View File

@ -167,8 +167,7 @@ class ChannelsPlayer(MediaPlayerEntity):
@property @property
def source_list(self): def source_list(self):
"""List of favorite channels.""" """List of favorite channels."""
sources = [channel["name"] for channel in self.favorite_channels] return [channel["name"] for channel in self.favorite_channels]
return sources
@property @property
def is_volume_muted(self): def is_volume_muted(self):

View File

@ -72,11 +72,10 @@ class CiscoMEDeviceScanner(DeviceScanner):
def get_device_name(self, device): def get_device_name(self, device):
"""Return the name of the given device or None if we don't know.""" """Return the name of the given device or None if we don't know."""
name = next( return next(
(result.clId for result in self.last_results if result.macaddr == device), (result.clId for result in self.last_results if result.macaddr == device),
None, None,
) )
return name
def get_extra_attributes(self, device): def get_extra_attributes(self, device):
"""Get extra attributes of a device. """Get extra attributes of a device.

View File

@ -396,6 +396,4 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
return unload_ok

View File

@ -65,7 +65,7 @@ async def _get_services(hass: HomeAssistant) -> list[dict[str, Any]]:
services: list[dict[str, Any]] services: list[dict[str, Any]]
if DATA_SERVICES in hass.data: if DATA_SERVICES in hass.data:
services = hass.data[DATA_SERVICES] services = hass.data[DATA_SERVICES]
return services return services # noqa: RET504
try: try:
services = await account_link.async_fetch_available_services(hass.data[DOMAIN]) services = await account_link.async_fetch_available_services(hass.data[DOMAIN])

View File

@ -50,8 +50,7 @@ STEP_USER_DATA_SCHEMA = vol.Schema(
def get_user_from_client(api_key, api_token): def get_user_from_client(api_key, api_token):
"""Get the user name from Coinbase API credentials.""" """Get the user name from Coinbase API credentials."""
client = Client(api_key, api_token) client = Client(api_key, api_token)
user = client.get_current_user() return client.get_current_user()
return user
async def validate_api(hass: HomeAssistant, data): async def validate_api(hass: HomeAssistant, data):

View File

@ -84,7 +84,7 @@ async def async_converse(
language = hass.config.language language = hass.config.language
_LOGGER.debug("Processing in %s: %s", language, text) _LOGGER.debug("Processing in %s: %s", language, text)
result = await method( return await method(
ConversationInput( ConversationInput(
text=text, text=text,
context=context, context=context,
@ -93,7 +93,6 @@ async def async_converse(
language=language, language=language,
) )
) )
return result
class AgentManager: class AgentManager:

View File

@ -240,7 +240,7 @@ class DefaultAgent(ConversationEntity):
slot_lists = self._make_slot_lists() slot_lists = self._make_slot_lists()
intent_context = self._make_intent_context(user_input) intent_context = self._make_intent_context(user_input)
result = await self.hass.async_add_executor_job( return await self.hass.async_add_executor_job(
self._recognize, self._recognize,
user_input, user_input,
lang_intents, lang_intents,
@ -249,8 +249,6 @@ class DefaultAgent(ConversationEntity):
language, language,
) )
return result
async def async_process(self, user_input: ConversationInput) -> ConversationResult: async def async_process(self, user_input: ConversationInput) -> ConversationResult:
"""Process a sentence.""" """Process a sentence."""
language = user_input.language or self.hass.config.language language = user_input.language or self.hass.config.language
@ -901,8 +899,7 @@ class DefaultAgent(ConversationEntity):
# Force rebuild on next use # Force rebuild on next use
self._trigger_intents = None self._trigger_intents = None
unregister = functools.partial(self._unregister_trigger, trigger_data) return functools.partial(self._unregister_trigger, trigger_data)
return unregister
def _rebuild_trigger_intents(self) -> None: def _rebuild_trigger_intents(self) -> None:
"""Rebuild the HassIL intents object from the current trigger sentences.""" """Rebuild the HassIL intents object from the current trigger sentences."""

View File

@ -64,10 +64,9 @@ class CPPMDeviceScanner(DeviceScanner):
def get_device_name(self, device): def get_device_name(self, device):
"""Retrieve device name.""" """Retrieve device name."""
name = next( return next(
(result["name"] for result in self.results if result["mac"] == device), None (result["name"] for result in self.results if result["mac"] == device), None
) )
return name
def get_cppm_data(self): def get_cppm_data(self):
"""Retrieve data from Aruba Clearpass and return parsed result.""" """Retrieve data from Aruba Clearpass and return parsed result."""

View File

@ -97,9 +97,7 @@ async def daikin_api_setup(
_LOGGER.error("Unexpected error creating device %s", host) _LOGGER.error("Unexpected error creating device %s", host)
return None return None
api = DaikinApi(device) return DaikinApi(device)
return api
class DaikinApi: class DaikinApi:

View File

@ -558,8 +558,7 @@ async def get_tracker(hass: HomeAssistant, config: ConfigType) -> DeviceTracker:
track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) track_new = defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)
devices = await async_load_config(yaml_path, hass, consider_home) devices = await async_load_config(yaml_path, hass, consider_home)
tracker = DeviceTracker(hass, consider_home, track_new, defaults, devices) return DeviceTracker(hass, consider_home, track_new, defaults, devices)
return tracker
class DeviceTracker: class DeviceTracker:

View File

@ -41,9 +41,7 @@ async def async_get_config_entry_diagnostics(
for gateway in gateways for gateway in gateways
] ]
diag_data = { return {
"entry": async_redact_data(entry.as_dict(), TO_REDACT), "entry": async_redact_data(entry.as_dict(), TO_REDACT),
"device_info": device_info, "device_info": device_info,
} }
return diag_data

View File

@ -51,13 +51,11 @@ class SmartPlugSwitch(DLinkEntity, SwitchEntity):
except ValueError: except ValueError:
total_consumption = None total_consumption = None
attrs = { return {
ATTR_TOTAL_CONSUMPTION: total_consumption, ATTR_TOTAL_CONSUMPTION: total_consumption,
ATTR_TEMPERATURE: temperature, ATTR_TEMPERATURE: temperature,
} }
return attrs
@property @property
def is_on(self) -> bool: def is_on(self) -> bool:
"""Return true if switch is on.""" """Return true if switch is on."""

View File

@ -339,11 +339,7 @@ class DlnaDmrFlowHandler(ConfigFlow, domain=DOMAIN):
entry.unique_id entry.unique_id
for entry in self._async_current_entries(include_ignore=False) for entry in self._async_current_entries(include_ignore=False)
} }
discoveries = [ return [disc for disc in discoveries if disc.ssdp_udn not in current_unique_ids]
disc for disc in discoveries if disc.ssdp_udn not in current_unique_ids
]
return discoveries
class DlnaDmrOptionsFlowHandler(OptionsFlow): class DlnaDmrOptionsFlowHandler(OptionsFlow):

View File

@ -179,8 +179,4 @@ class DlnaDmsFlowHandler(ConfigFlow, domain=DOMAIN):
entry.unique_id entry.unique_id
for entry in self._async_current_entries(include_ignore=False) for entry in self._async_current_entries(include_ignore=False)
} }
discoveries = [ return [disc for disc in discoveries if disc.ssdp_udn not in current_unique_ids]
disc for disc in discoveries if disc.ssdp_udn not in current_unique_ids
]
return discoveries

View File

@ -516,7 +516,7 @@ class DmsDeviceSource:
if isinstance(child, didl_lite.DidlObject) if isinstance(child, didl_lite.DidlObject)
] ]
media_source = BrowseMediaSource( return BrowseMediaSource(
domain=DOMAIN, domain=DOMAIN,
identifier=self._make_identifier(Action.SEARCH, query), identifier=self._make_identifier(Action.SEARCH, query),
media_class=MediaClass.DIRECTORY, media_class=MediaClass.DIRECTORY,
@ -527,8 +527,6 @@ class DmsDeviceSource:
children=children, children=children,
) )
return media_source
def _didl_to_play_media(self, item: didl_lite.DidlObject) -> DidlPlayMedia: def _didl_to_play_media(self, item: didl_lite.DidlObject) -> DidlPlayMedia:
"""Return the first playable resource from a DIDL-Lite object.""" """Return the first playable resource from a DIDL-Lite object."""
assert self._device assert self._device
@ -583,7 +581,7 @@ class DmsDeviceSource:
mime_type = _resource_mime_type(item.res[0]) if item.res else None mime_type = _resource_mime_type(item.res[0]) if item.res else None
media_content_type = mime_type or item.upnp_class media_content_type = mime_type or item.upnp_class
media_source = BrowseMediaSource( return BrowseMediaSource(
domain=DOMAIN, domain=DOMAIN,
identifier=self._make_identifier(Action.OBJECT, item.id), identifier=self._make_identifier(Action.OBJECT, item.id),
media_class=MEDIA_CLASS_MAP.get(item.upnp_class, ""), media_class=MEDIA_CLASS_MAP.get(item.upnp_class, ""),
@ -595,8 +593,6 @@ class DmsDeviceSource:
thumbnail=self._didl_thumbnail_url(item), thumbnail=self._didl_thumbnail_url(item),
) )
return media_source
def _didl_thumbnail_url(self, item: didl_lite.DidlObject) -> str | None: def _didl_thumbnail_url(self, item: didl_lite.DidlObject) -> str | None:
"""Return absolute URL of a thumbnail for a DIDL-Lite object. """Return absolute URL of a thumbnail for a DIDL-Lite object.

View File

@ -22,7 +22,7 @@ async def async_get_device_diagnostics(
station = ecowitt.stations[station_id] station = ecowitt.stations[station_id]
data = { return {
"device": { "device": {
"name": station.station, "name": station.station,
"model": station.model, "model": station.model,
@ -36,5 +36,3 @@ async def async_get_device_diagnostics(
if sensor.station.key == station_id if sensor.station.key == station_id
}, },
} }
return data

View File

@ -102,7 +102,7 @@ class EgardiaAlarm(alarm.AlarmControlPanelEntity):
def lookupstatusfromcode(self, statuscode): def lookupstatusfromcode(self, statuscode):
"""Look at the rs_codes and returns the status from the code.""" """Look at the rs_codes and returns the status from the code."""
status = next( return next(
( (
status_group.upper() status_group.upper()
for status_group, codes in self._rs_codes.items() for status_group, codes in self._rs_codes.items()
@ -111,7 +111,6 @@ class EgardiaAlarm(alarm.AlarmControlPanelEntity):
), ),
"UNKNOWN", "UNKNOWN",
) )
return status
def parsestatus(self, status): def parsestatus(self, status):
"""Parse the status.""" """Parse the status."""

View File

@ -73,5 +73,4 @@ class ElectricKiwiLocalOAuth2Implementation(AuthImplementation):
resp = await session.post(self.token_url, data=data, headers=headers) resp = await session.post(self.token_url, data=data, headers=headers)
resp.raise_for_status() resp.raise_for_status()
resp_json = cast(dict, await resp.json()) return cast(dict, await resp.json())
return resp_json

View File

@ -81,10 +81,7 @@ class EnOceanFlowHandler(ConfigFlow, domain=DOMAIN):
async def validate_enocean_conf(self, user_input) -> bool: async def validate_enocean_conf(self, user_input) -> bool:
"""Return True if the user_input contains a valid dongle path.""" """Return True if the user_input contains a valid dongle path."""
dongle_path = user_input[CONF_DEVICE] dongle_path = user_input[CONF_DEVICE]
path_is_valid = await self.hass.async_add_executor_job( return await self.hass.async_add_executor_job(dongle.validate_path, dongle_path)
dongle.validate_path, dongle_path
)
return path_is_valid
def create_enocean_entry(self, user_input): def create_enocean_entry(self, user_input):
"""Create an entry for the provided configuration.""" """Create an entry for the provided configuration."""

View File

@ -21,9 +21,7 @@ async def async_get_config_entry_diagnostics(
coordinators = hass.data[DOMAIN][config_entry.entry_id] coordinators = hass.data[DOMAIN][config_entry.entry_id]
weather_coord = coordinators["weather_coordinator"] weather_coord = coordinators["weather_coordinator"]
diagnostics_data = { return {
"config_entry_data": async_redact_data(dict(config_entry.data), TO_REDACT), "config_entry_data": async_redact_data(dict(config_entry.data), TO_REDACT),
"weather_data": dict(weather_coord.ec_data.conditions), "weather_data": dict(weather_coord.ec_data.conditions),
} }
return diagnostics_data

View File

@ -70,15 +70,13 @@ def _validate_and_create_auth(data: dict) -> dict[str, Any]:
ezviz_token = ezviz_client.login() ezviz_token = ezviz_client.login()
auth_data = { return {
CONF_SESSION_ID: ezviz_token[CONF_SESSION_ID], CONF_SESSION_ID: ezviz_token[CONF_SESSION_ID],
CONF_RFSESSION_ID: ezviz_token[CONF_RFSESSION_ID], CONF_RFSESSION_ID: ezviz_token[CONF_RFSESSION_ID],
CONF_URL: ezviz_token["api_url"], CONF_URL: ezviz_token["api_url"],
CONF_TYPE: ATTR_TYPE_CLOUD, CONF_TYPE: ATTR_TYPE_CLOUD,
} }
return auth_data
def _test_camera_rtsp_creds(data: dict) -> None: def _test_camera_rtsp_creds(data: dict) -> None:
"""Try DESCRIBE on RTSP camera with credentials.""" """Try DESCRIBE on RTSP camera with credentials."""

View File

@ -133,10 +133,9 @@ async def async_get_image(
else: else:
extra_cmd += " " + size_cmd extra_cmd += " " + size_cmd
image = await asyncio.shield( return await asyncio.shield(
ffmpeg.get_image(input_source, output_format=output_format, extra_cmd=extra_cmd) ffmpeg.get_image(input_source, output_format=output_format, extra_cmd=extra_cmd)
) )
return image
class FFmpegManager: class FFmpegManager:

View File

@ -63,7 +63,7 @@ class ResponseBinarySensor(CoordinatorEntity, BinarySensorEntity):
return attr return attr
data = self.coordinator.data data = self.coordinator.data
attr = { return {
key: data[key] key: data[key]
for key in ( for key in (
"start_time", "start_time",
@ -77,5 +77,3 @@ class ResponseBinarySensor(CoordinatorEntity, BinarySensorEntity):
) )
if key in data if key in data
} }
return attr

View File

@ -71,7 +71,7 @@ class ResponseSwitch(SwitchEntity):
return attr return attr
data = self._state_attributes data = self._state_attributes
attr = { return {
key: data[key] key: data[key]
for key in ( for key in (
"user_name", "user_name",
@ -87,8 +87,6 @@ class ResponseSwitch(SwitchEntity):
if key in data if key in data
} }
return attr
async def async_turn_on(self, **kwargs: Any) -> None: async def async_turn_on(self, **kwargs: Any) -> None:
"""Send Acknowledge response status.""" """Send Acknowledge response status."""
await self.async_set_response(True) await self.async_set_response(True)

View File

@ -91,9 +91,7 @@ class FliprConfigFlow(ConfigFlow, domain=DOMAIN):
# Instantiates the flipr API that does not require async since it is has no network access. # Instantiates the flipr API that does not require async since it is has no network access.
client = FliprAPIRestClient(self._username, self._password) client = FliprAPIRestClient(self._username, self._password)
flipr_ids = await self.hass.async_add_executor_job(client.search_flipr_ids) return await self.hass.async_add_executor_job(client.search_flipr_ids)
return flipr_ids
async def async_step_flipr_id( async def async_step_flipr_id(
self, user_input: dict[str, str] | None = None self, user_input: dict[str, str] | None = None

View File

@ -39,8 +39,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
def get_files_list(folder_path: str, filter_term: str) -> list[str]: def get_files_list(folder_path: str, filter_term: str) -> list[str]:
"""Return the list of files, applying filter.""" """Return the list of files, applying filter."""
query = folder_path + filter_term query = folder_path + filter_term
files_list = glob.glob(query) return glob.glob(query)
return files_list
def get_size(files_list: list[str]) -> int: def get_size(files_list: list[str]) -> int:

View File

@ -21,7 +21,7 @@ async def async_get_config_entry_diagnostics(
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
avm_wrapper: AvmWrapper = hass.data[DOMAIN][entry.entry_id] avm_wrapper: AvmWrapper = hass.data[DOMAIN][entry.entry_id]
diag_data = { return {
"entry": async_redact_data(entry.as_dict(), TO_REDACT), "entry": async_redact_data(entry.as_dict(), TO_REDACT),
"device_info": { "device_info": {
"model": avm_wrapper.model, "model": avm_wrapper.model,
@ -51,5 +51,3 @@ async def async_get_config_entry_diagnostics(
"wan_link_properties": await avm_wrapper.async_get_wan_link_properties(), "wan_link_properties": await avm_wrapper.async_get_wan_link_properties(),
}, },
} }
return diag_data

View File

@ -94,7 +94,7 @@ async def browse_top_level(current_mode, afsapi: AFSAPI):
for top_level_media_content_id, name in TOP_LEVEL_DIRECTORIES.items() for top_level_media_content_id, name in TOP_LEVEL_DIRECTORIES.items()
] ]
library_info = BrowseMedia( return BrowseMedia(
media_class=MediaClass.DIRECTORY, media_class=MediaClass.DIRECTORY,
media_content_id="library", media_content_id="library",
media_content_type=MediaType.CHANNELS, media_content_type=MediaType.CHANNELS,
@ -105,8 +105,6 @@ async def browse_top_level(current_mode, afsapi: AFSAPI):
children_media_class=MediaClass.DIRECTORY, children_media_class=MediaClass.DIRECTORY,
) )
return library_info
async def browse_node( async def browse_node(
afsapi: AFSAPI, afsapi: AFSAPI,

View File

@ -18,9 +18,7 @@ async def async_get_config_entry_diagnostics(
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
coordinator: GiosDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id] coordinator: GiosDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
diagnostics_data = { return {
"config_entry": config_entry.as_dict(), "config_entry": config_entry.as_dict(),
"coordinator_data": asdict(coordinator.data), "coordinator_data": asdict(coordinator.data),
} }
return diagnostics_data

View File

@ -18,7 +18,7 @@ async def async_get_config_entry_diagnostics(
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
inverter: Inverter = hass.data[DOMAIN][config_entry.entry_id][KEY_INVERTER] inverter: Inverter = hass.data[DOMAIN][config_entry.entry_id][KEY_INVERTER]
diagnostics_data = { return {
"config_entry": config_entry.as_dict(), "config_entry": config_entry.as_dict(),
"inverter": { "inverter": {
"model_name": inverter.model_name, "model_name": inverter.model_name,
@ -32,5 +32,3 @@ async def async_get_config_entry_diagnostics(
"arm_svn_version": inverter.arm_svn_version, "arm_svn_version": inverter.arm_svn_version,
}, },
} }
return diagnostics_data

View File

@ -139,9 +139,7 @@ async def async_devices_sync(
await data.config.async_connect_agent_user(agent_user_id) await data.config.async_connect_agent_user(agent_user_id)
devices = await async_devices_sync_response(hass, data.config, agent_user_id) devices = await async_devices_sync_response(hass, data.config, agent_user_id)
response = create_sync_response(agent_user_id, devices) return create_sync_response(agent_user_id, devices)
return response
@HANDLERS.register("action.devices.QUERY") @HANDLERS.register("action.devices.QUERY")

View File

@ -1927,9 +1927,7 @@ class ModesTrait(_Trait):
# Shortcut since all domains are currently unique # Shortcut since all domains are currently unique
break break
payload = {"availableModes": modes} return {"availableModes": modes}
return payload
def query_attributes(self): def query_attributes(self):
"""Return current modes.""" """Return current modes."""
@ -2104,9 +2102,7 @@ class InputSelectorTrait(_Trait):
for source in sourcelist for source in sourcelist
] ]
payload = {"availableInputs": inputs, "orderedInputs": True} return {"availableInputs": inputs, "orderedInputs": True}
return payload
def query_attributes(self): def query_attributes(self):
"""Return current modes.""" """Return current modes."""

View File

@ -220,12 +220,11 @@ class PulseCounter(GEMSensor):
if self._sensor.pulses_per_second is None: if self._sensor.pulses_per_second is None:
return None return None
result = ( return (
self._sensor.pulses_per_second self._sensor.pulses_per_second
* self._counted_quantity_per_pulse * self._counted_quantity_per_pulse
* self._seconds_per_time_unit * self._seconds_per_time_unit
) )
return result
@property @property
def _seconds_per_time_unit(self) -> int: def _seconds_per_time_unit(self) -> int:

View File

@ -48,17 +48,13 @@ class HarmonyData(HarmonySubscriberMixin):
def activity_names(self) -> list[str]: def activity_names(self) -> list[str]:
"""Names of all the remotes activities.""" """Names of all the remotes activities."""
activity_infos = self.activities activity_infos = self.activities
activities = [activity["label"] for activity in activity_infos] return [activity["label"] for activity in activity_infos]
return activities
@property @property
def device_names(self): def device_names(self):
"""Names of all of the devices connected to the hub.""" """Names of all of the devices connected to the hub."""
device_infos = self._client.config.get("device", []) device_infos = self._client.config.get("device", [])
devices = [device["label"] for device in device_infos] return [device["label"] for device in device_infos]
return devices
@property @property
def unique_id(self): def unique_id(self):

View File

@ -101,7 +101,7 @@ class HKOUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
def _convert_current(self, data: dict[str, Any]) -> dict[str, Any]: def _convert_current(self, data: dict[str, Any]) -> dict[str, Any]:
"""Return temperature and humidity in the appropriate format.""" """Return temperature and humidity in the appropriate format."""
current = { return {
API_HUMIDITY: data[API_HUMIDITY][API_DATA][0][API_VALUE], API_HUMIDITY: data[API_HUMIDITY][API_DATA][0][API_VALUE],
API_TEMPERATURE: next( API_TEMPERATURE: next(
( (
@ -112,12 +112,11 @@ class HKOUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
0, 0,
), ),
} }
return current
def _convert_forecast(self, data: dict[str, Any]) -> dict[str, Any]: def _convert_forecast(self, data: dict[str, Any]) -> dict[str, Any]:
"""Return daily forecast in the appropriate format.""" """Return daily forecast in the appropriate format."""
date = data[API_FORECAST_DATE] date = data[API_FORECAST_DATE]
forecast = { return {
ATTR_FORECAST_CONDITION: self._convert_icon_condition( ATTR_FORECAST_CONDITION: self._convert_icon_condition(
data[API_FORECAST_ICON], data[API_FORECAST_WEATHER] data[API_FORECAST_ICON], data[API_FORECAST_WEATHER]
), ),
@ -125,7 +124,6 @@ class HKOUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
ATTR_FORECAST_TEMP_LOW: data[API_FORECAST_MIN_TEMP][API_VALUE], ATTR_FORECAST_TEMP_LOW: data[API_FORECAST_MIN_TEMP][API_VALUE],
ATTR_FORECAST_TIME: f"{date[0:4]}-{date[4:6]}-{date[6:8]}T00:00:00+08:00", ATTR_FORECAST_TIME: f"{date[0:4]}-{date[4:6]}-{date[6:8]}T00:00:00+08:00",
} }
return forecast
def _convert_icon_condition(self, icon_code: int, info: str) -> str: def _convert_icon_condition(self, icon_code: int, info: str) -> str:
"""Return the condition corresponding to an icon code.""" """Return the condition corresponding to an icon code."""

View File

@ -259,7 +259,7 @@ class ExposedEntities:
if assistant in registry_entry.options: if assistant in registry_entry.options:
if "should_expose" in registry_entry.options[assistant]: if "should_expose" in registry_entry.options[assistant]:
should_expose = registry_entry.options[assistant]["should_expose"] should_expose = registry_entry.options[assistant]["should_expose"]
return should_expose return should_expose # noqa: RET504
if self.async_get_expose_new_entities(assistant): if self.async_get_expose_new_entities(assistant):
should_expose = self._is_default_exposed(entity_id, registry_entry) should_expose = self._is_default_exposed(entity_id, registry_entry)
@ -286,7 +286,7 @@ class ExposedEntities:
) and assistant in exposed_entity.assistants: ) and assistant in exposed_entity.assistants:
if "should_expose" in exposed_entity.assistants[assistant]: if "should_expose" in exposed_entity.assistants[assistant]:
should_expose = exposed_entity.assistants[assistant]["should_expose"] should_expose = exposed_entity.assistants[assistant]["should_expose"]
return should_expose return should_expose # noqa: RET504
if self.async_get_expose_new_entities(assistant): if self.async_get_expose_new_entities(assistant):
should_expose = self._is_default_exposed(entity_id, None) should_expose = self._is_default_exposed(entity_id, None)

View File

@ -70,7 +70,6 @@ class RequestDataValidator:
f"Message format incorrect: {err}", HTTPStatus.BAD_REQUEST f"Message format incorrect: {err}", HTTPStatus.BAD_REQUEST
) )
result = await method(view, request, data, *args, **kwargs) return await method(view, request, data, *args, **kwargs)
return result
return wrapper return wrapper

View File

@ -82,8 +82,7 @@ async def _async_get_image(image_entity: ImageEntity, timeout: int) -> Image:
async with asyncio.timeout(timeout): async with asyncio.timeout(timeout):
if image_bytes := await image_entity.async_image(): if image_bytes := await image_entity.async_image():
content_type = valid_image_content_type(image_entity.content_type) content_type = valid_image_content_type(image_entity.content_type)
image = Image(content_type, image_bytes) return Image(content_type, image_bytes)
return image
raise HomeAssistantError("Unable to get image") raise HomeAssistantError("Unable to get image")

View File

@ -31,9 +31,7 @@ def _async_get_diagnostics(
redacted_config = async_redact_data(entry.data, REDACT_CONFIG) redacted_config = async_redact_data(entry.data, REDACT_CONFIG)
coordinator: ImapDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] coordinator: ImapDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
data = { return {
"config": redacted_config, "config": redacted_config,
"event": coordinator.diagnostics_data, "event": coordinator.diagnostics_data,
} }
return data

View File

@ -139,8 +139,7 @@ def property_to_dict(prop):
modified = value == prop.new_value modified = value == prop.new_value
if prop.value_type in [ToggleMode, RelayMode] or prop.name == RAMP_RATE_IN_SEC: if prop.value_type in [ToggleMode, RelayMode] or prop.name == RAMP_RATE_IN_SEC:
value = str(value).lower() value = str(value).lower()
prop_dict = {"name": prop.name, "value": value, "modified": modified} return {"name": prop.name, "value": value, "modified": modified}
return prop_dict
def update_property(device, prop_name, value): def update_property(device, prop_name, value):

View File

@ -466,12 +466,10 @@ class IntegrationSensor(RestoreSensor):
@property @property
def extra_state_attributes(self) -> dict[str, str] | None: def extra_state_attributes(self) -> dict[str, str] | None:
"""Return the state attributes of the sensor.""" """Return the state attributes of the sensor."""
state_attr = { return {
ATTR_SOURCE_ID: self._source_entity, ATTR_SOURCE_ID: self._source_entity,
} }
return state_attr
@property @property
def extra_restore_state_data(self) -> IntegrationSensorExtraStoredData: def extra_restore_state_data(self) -> IntegrationSensorExtraStoredData:
"""Return sensor specific state data to be restored.""" """Return sensor specific state data to be restored."""

View File

@ -61,8 +61,7 @@ class IntellifireFlameControlEntity(IntellifireEntity, NumberEntity):
def native_value(self) -> float | None: def native_value(self) -> float | None:
"""Return the current Flame Height segment number value.""" """Return the current Flame Height segment number value."""
# UI uses 1-5 for flame height, backing lib uses 0-4 # UI uses 1-5 for flame height, backing lib uses 0-4
value = self.coordinator.read_api.data.flameheight + 1 return self.coordinator.read_api.data.flameheight + 1
return value
async def async_set_native_value(self, value: float) -> None: async def async_set_native_value(self, value: float) -> None:
"""Slider change.""" """Slider change."""

View File

@ -286,7 +286,7 @@ class JellyfinSource(MediaSource):
mime_type = _media_mime_type(track) mime_type = _media_mime_type(track)
thumbnail_url = self._get_thumbnail_url(track) thumbnail_url = self._get_thumbnail_url(track)
result = BrowseMediaSource( return BrowseMediaSource(
domain=DOMAIN, domain=DOMAIN,
identifier=track_id, identifier=track_id,
media_class=MediaClass.TRACK, media_class=MediaClass.TRACK,
@ -297,8 +297,6 @@ class JellyfinSource(MediaSource):
thumbnail=thumbnail_url, thumbnail=thumbnail_url,
) )
return result
async def _build_movie_library( async def _build_movie_library(
self, library: dict[str, Any], include_children: bool self, library: dict[str, Any], include_children: bool
) -> BrowseMediaSource: ) -> BrowseMediaSource:
@ -347,7 +345,7 @@ class JellyfinSource(MediaSource):
mime_type = _media_mime_type(movie) mime_type = _media_mime_type(movie)
thumbnail_url = self._get_thumbnail_url(movie) thumbnail_url = self._get_thumbnail_url(movie)
result = BrowseMediaSource( return BrowseMediaSource(
domain=DOMAIN, domain=DOMAIN,
identifier=movie_id, identifier=movie_id,
media_class=MediaClass.MOVIE, media_class=MediaClass.MOVIE,
@ -358,8 +356,6 @@ class JellyfinSource(MediaSource):
thumbnail=thumbnail_url, thumbnail=thumbnail_url,
) )
return result
async def _build_tv_library( async def _build_tv_library(
self, library: dict[str, Any], include_children: bool self, library: dict[str, Any], include_children: bool
) -> BrowseMediaSource: ) -> BrowseMediaSource:
@ -486,7 +482,7 @@ class JellyfinSource(MediaSource):
mime_type = _media_mime_type(episode) mime_type = _media_mime_type(episode)
thumbnail_url = self._get_thumbnail_url(episode) thumbnail_url = self._get_thumbnail_url(episode)
result = BrowseMediaSource( return BrowseMediaSource(
domain=DOMAIN, domain=DOMAIN,
identifier=episode_id, identifier=episode_id,
media_class=MediaClass.EPISODE, media_class=MediaClass.EPISODE,
@ -497,8 +493,6 @@ class JellyfinSource(MediaSource):
thumbnail=thumbnail_url, thumbnail=thumbnail_url,
) )
return result
async def _get_children( async def _get_children(
self, parent_id: str, item_type: str self, parent_id: str, item_type: str
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:

View File

@ -300,7 +300,7 @@ class KodiConfigFlow(ConfigFlow, domain=DOMAIN):
@callback @callback
def _get_data(self): def _get_data(self):
data = { return {
CONF_NAME: self._name, CONF_NAME: self._name,
CONF_HOST: self._host, CONF_HOST: self._host,
CONF_PORT: self._port, CONF_PORT: self._port,
@ -311,8 +311,6 @@ class KodiConfigFlow(ConfigFlow, domain=DOMAIN):
CONF_TIMEOUT: DEFAULT_TIMEOUT, CONF_TIMEOUT: DEFAULT_TIMEOUT,
} }
return data
class CannotConnect(HomeAssistantError): class CannotConnect(HomeAssistantError):
"""Error to indicate we cannot connect.""" """Error to indicate we cannot connect."""

View File

@ -235,8 +235,7 @@ class SettingDataUpdateCoordinator(
_LOGGER.debug("Fetching %s for %s", self.name, self._fetch) _LOGGER.debug("Fetching %s for %s", self.name, self._fetch)
fetched_data = await client.get_setting_values(self._fetch) return await client.get_setting_values(self._fetch)
return fetched_data
class PlenticoreSelectUpdateCoordinator(DataUpdateCoordinator[_DataT]): # pylint: disable=hass-enforce-coordinator-module class PlenticoreSelectUpdateCoordinator(DataUpdateCoordinator[_DataT]): # pylint: disable=hass-enforce-coordinator-module
@ -295,9 +294,7 @@ class SelectDataUpdateCoordinator(
_LOGGER.debug("Fetching select %s for %s", self.name, self._fetch) _LOGGER.debug("Fetching select %s for %s", self.name, self._fetch)
fetched_data = await self._async_get_current_option(self._fetch) return await self._async_get_current_option(self._fetch)
return fetched_data
async def _async_get_current_option( async def _async_get_current_option(
self, self,
@ -313,8 +310,7 @@ class SelectDataUpdateCoordinator(
continue continue
for option in val.values(): for option in val.values():
if option[all_option] == "1": if option[all_option] == "1":
fetched = {mid: {cast(str, pids[0]): all_option}} return {mid: {cast(str, pids[0]): all_option}}
return fetched
return {mid: {cast(str, pids[0]): "None"}} return {mid: {cast(str, pids[0]): "None"}}
return {} return {}

View File

@ -35,5 +35,4 @@ async def async_unload_entry(
hass: core.HomeAssistant, entry: config_entries.ConfigEntry hass: core.HomeAssistant, entry: config_entries.ConfigEntry
) -> bool: ) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
result = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
return result

View File

@ -957,8 +957,7 @@ class LightEntity(ToggleEntity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
@property @property
def _light_internal_rgbw_color(self) -> tuple[int, int, int, int] | None: def _light_internal_rgbw_color(self) -> tuple[int, int, int, int] | None:
"""Return the rgbw color value [int, int, int, int].""" """Return the rgbw color value [int, int, int, int]."""
rgbw_color = self.rgbw_color return self.rgbw_color
return rgbw_color
@cached_property @cached_property
def rgbww_color(self) -> tuple[int, int, int, int, int] | None: def rgbww_color(self) -> tuple[int, int, int, int, int] | None:

View File

@ -53,15 +53,13 @@ async def validate_input(
finally: finally:
await hub.close() await hub.close()
info = { return {
"email": data["email"], "email": data["email"],
"password": data["password"], "password": data["password"],
"sites": sites, "sites": sites,
"device_id": device_id, "device_id": device_id,
} }
return info
class LinearGarageDoorConfigFlow(ConfigFlow, domain=DOMAIN): class LinearGarageDoorConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Linear Garage Door.""" """Handle a config flow for Linear Garage Door."""

View File

@ -82,7 +82,7 @@ def devices_stmt(
json_quotable_device_ids: list[str], json_quotable_device_ids: list[str],
) -> StatementLambdaElement: ) -> StatementLambdaElement:
"""Generate a logbook query for multiple devices.""" """Generate a logbook query for multiple devices."""
stmt = lambda_stmt( return lambda_stmt(
lambda: _apply_devices_context_union( lambda: _apply_devices_context_union(
select_events_without_states(start_day, end_day, event_type_ids).where( select_events_without_states(start_day, end_day, event_type_ids).where(
apply_event_device_id_matchers(json_quotable_device_ids) apply_event_device_id_matchers(json_quotable_device_ids)
@ -93,7 +93,6 @@ def devices_stmt(
json_quotable_device_ids, json_quotable_device_ids,
).order_by(Events.time_fired_ts) ).order_by(Events.time_fired_ts)
) )
return stmt
def apply_event_device_id_matchers( def apply_event_device_id_matchers(

View File

@ -110,7 +110,7 @@ def entities_devices_stmt(
json_quoted_device_ids: list[str], json_quoted_device_ids: list[str],
) -> StatementLambdaElement: ) -> StatementLambdaElement:
"""Generate a logbook query for multiple entities.""" """Generate a logbook query for multiple entities."""
stmt = lambda_stmt( return lambda_stmt(
lambda: _apply_entities_devices_context_union( lambda: _apply_entities_devices_context_union(
select_events_without_states(start_day, end_day, event_type_ids).where( select_events_without_states(start_day, end_day, event_type_ids).where(
_apply_event_entity_id_device_id_matchers( _apply_event_entity_id_device_id_matchers(
@ -125,7 +125,6 @@ def entities_devices_stmt(
json_quoted_device_ids, json_quoted_device_ids,
).order_by(Events.time_fired_ts) ).order_by(Events.time_fired_ts)
) )
return stmt
def _apply_event_entity_id_device_id_matchers( def _apply_event_entity_id_device_id_matchers(

View File

@ -71,11 +71,10 @@ class LuciDeviceScanner(DeviceScanner):
def get_device_name(self, device): def get_device_name(self, device):
"""Return the name of the given device or None if we don't know.""" """Return the name of the given device or None if we don't know."""
name = next( return next(
(result.hostname for result in self.last_results if result.mac == device), (result.hostname for result in self.last_results if result.mac == device),
None, None,
) )
return name
def get_extra_attributes(self, device): def get_extra_attributes(self, device):
"""Get extra attributes of a device. """Get extra attributes of a device.

View File

@ -109,7 +109,7 @@ def get_node_from_device_entry(
if server_info is None: if server_info is None:
raise RuntimeError("Matter server information is not available") raise RuntimeError("Matter server information is not available")
node = next( return next(
( (
node node
for node in matter_client.get_nodes() for node in matter_client.get_nodes()
@ -118,5 +118,3 @@ def get_node_from_device_entry(
), ),
None, None,
) )
return node

View File

@ -93,12 +93,10 @@ class LocalSource(MediaSource):
else: else:
source_dir_id, location = None, "" source_dir_id, location = None, ""
result = await self.hass.async_add_executor_job( return await self.hass.async_add_executor_job(
self._browse_media, source_dir_id, location self._browse_media, source_dir_id, location
) )
return result
def _browse_media( def _browse_media(
self, source_dir_id: str | None, location: str self, source_dir_id: str | None, location: str
) -> BrowseMediaSource: ) -> BrowseMediaSource:

View File

@ -330,12 +330,11 @@ class AtwDeviceZoneClimate(MelCloudClimate):
@property @property
def extra_state_attributes(self) -> dict[str, Any]: def extra_state_attributes(self) -> dict[str, Any]:
"""Return the optional state attributes with device specific additions.""" """Return the optional state attributes with device specific additions."""
data = { return {
ATTR_STATUS: ATW_ZONE_HVAC_MODE_LOOKUP.get( ATTR_STATUS: ATW_ZONE_HVAC_MODE_LOOKUP.get(
self._zone.status, self._zone.status self._zone.status, self._zone.status
) )
} }
return data
@property @property
def hvac_mode(self) -> HVACMode: def hvac_mode(self) -> HVACMode:

View File

@ -73,8 +73,7 @@ class AtwWaterHeater(WaterHeaterEntity):
@property @property
def extra_state_attributes(self) -> dict[str, Any] | None: def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the optional state attributes with device specific additions.""" """Return the optional state attributes with device specific additions."""
data = {ATTR_STATUS: self._device.status} return {ATTR_STATUS: self._device.status}
return data
@property @property
def temperature_unit(self) -> str: def temperature_unit(self) -> str:

View File

@ -49,5 +49,4 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry.""" """Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
return unload_ok

View File

@ -146,8 +146,7 @@ class MjpegCamera(Camera):
async with asyncio.timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
response = await websession.get(self._still_image_url, auth=self._auth) response = await websession.get(self._still_image_url, auth=self._auth)
image = await response.read() return await response.read()
return image
except TimeoutError: except TimeoutError:
LOGGER.error("Timeout getting camera image from %s", self.name) LOGGER.error("Timeout getting camera image from %s", self.name)

View File

@ -104,8 +104,7 @@ def _convert_legacy_encryption_key(key: str) -> bytes:
keylen = SecretBox.KEY_SIZE keylen = SecretBox.KEY_SIZE
key_bytes = key.encode("utf-8") key_bytes = key.encode("utf-8")
key_bytes = key_bytes[:keylen] key_bytes = key_bytes[:keylen]
key_bytes = key_bytes.ljust(keylen, b"\0") return key_bytes.ljust(keylen, b"\0")
return key_bytes
def decrypt_payload_legacy(key: str, ciphertext: bytes) -> JsonValueType | None: def decrypt_payload_legacy(key: str, ciphertext: bytes) -> JsonValueType | None:

View File

@ -187,7 +187,7 @@ async def async_subscribe(
translation_domain=DOMAIN, translation_domain=DOMAIN,
translation_placeholders={"topic": topic}, translation_placeholders={"topic": topic},
) from exc ) from exc
async_remove = await mqtt_data.client.async_subscribe( return await mqtt_data.client.async_subscribe(
topic, topic,
catch_log_exception( catch_log_exception(
msg_callback, msg_callback,
@ -199,7 +199,6 @@ async def async_subscribe(
qos, qos,
encoding, encoding,
) )
return async_remove
@bind_hass @bind_hass

View File

@ -99,7 +99,6 @@ async def async_attach_trigger(
"Attaching MQTT trigger for topic: '%s', payload: '%s'", topic, wanted_payload "Attaching MQTT trigger for topic: '%s', payload: '%s'", topic, wanted_payload
) )
remove = await mqtt.async_subscribe( return await mqtt.async_subscribe(
hass, topic, mqtt_automation_listener, encoding=encoding, qos=qos hass, topic, mqtt_automation_listener, encoding=encoding, qos=qos
) )
return remove

View File

@ -218,8 +218,7 @@ def valid_birth_will(config: ConfigType) -> ConfigType:
def get_mqtt_data(hass: HomeAssistant) -> MqttData: def get_mqtt_data(hass: HomeAssistant) -> MqttData:
"""Return typed MqttData from hass.data[DATA_MQTT].""" """Return typed MqttData from hass.data[DATA_MQTT]."""
mqtt_data: MqttData mqtt_data: MqttData = hass.data[DATA_MQTT]
mqtt_data = hass.data[DATA_MQTT]
return mqtt_data return mqtt_data

View File

@ -63,7 +63,7 @@ def is_persistence_file(value: str) -> str:
def _get_schema_common(user_input: dict[str, str]) -> dict: def _get_schema_common(user_input: dict[str, str]) -> dict:
"""Create a schema with options common to all gateway types.""" """Create a schema with options common to all gateway types."""
schema = { return {
vol.Required( vol.Required(
CONF_VERSION, CONF_VERSION,
description={ description={
@ -72,7 +72,6 @@ def _get_schema_common(user_input: dict[str, str]) -> dict:
): str, ): str,
vol.Optional(CONF_PERSISTENCE_FILE): str, vol.Optional(CONF_PERSISTENCE_FILE): str,
} }
return schema
def _validate_version(version: str) -> dict[str, str]: def _validate_version(version: str) -> dict[str, str]:

View File

@ -129,7 +129,7 @@ async def setup_gateway(
) -> BaseAsyncGateway | None: ) -> BaseAsyncGateway | None:
"""Set up the Gateway for the given ConfigEntry.""" """Set up the Gateway for the given ConfigEntry."""
ready_gateway = await _get_gateway( return await _get_gateway(
hass, hass,
gateway_type=entry.data[CONF_GATEWAY_TYPE], gateway_type=entry.data[CONF_GATEWAY_TYPE],
device=entry.data[CONF_DEVICE], device=entry.data[CONF_DEVICE],
@ -144,7 +144,6 @@ async def setup_gateway(
topic_out_prefix=entry.data.get(CONF_TOPIC_OUT_PREFIX), topic_out_prefix=entry.data.get(CONF_TOPIC_OUT_PREFIX),
retain=entry.data.get(CONF_RETAIN, False), retain=entry.data.get(CONF_RETAIN, False),
) )
return ready_gateway
async def _get_gateway( async def _get_gateway(

View File

@ -152,7 +152,7 @@ def get_child_schema(
"""Return a child schema.""" """Return a child schema."""
set_req = gateway.const.SetReq set_req = gateway.const.SetReq
child_schema = child.get_schema(gateway.protocol_version) child_schema = child.get_schema(gateway.protocol_version)
schema = child_schema.extend( return child_schema.extend(
{ {
vol.Required( vol.Required(
set_req[name].value, msg=invalid_msg(gateway, child, name) set_req[name].value, msg=invalid_msg(gateway, child, name)
@ -161,7 +161,6 @@ def get_child_schema(
}, },
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
return schema
def invalid_msg( def invalid_msg(

View File

@ -38,8 +38,7 @@ class MyStromView(HomeAssistantView):
async def get(self, request): async def get(self, request):
"""Handle the GET request received from a myStrom button.""" """Handle the GET request received from a myStrom button."""
res = await self._handle(request.app[KEY_HASS], request.query) return await self._handle(request.app[KEY_HASS], request.query)
return res
async def _handle(self, hass, data): async def _handle(self, hass, data):
"""Handle requests to the myStrom endpoint.""" """Handle requests to the myStrom endpoint."""

View File

@ -34,11 +34,7 @@ def get_description(device_point: DevicePoint) -> BinarySensorEntityDescription
2. Default to None 2. Default to None
""" """
prefix, _, _ = device_point.category.partition(" ") prefix, _, _ = device_point.category.partition(" ")
description = CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get( return CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get(device_point.parameter_id)
device_point.parameter_id
)
return description
async def async_setup_entry( async def async_setup_entry(

View File

@ -39,9 +39,7 @@ async def async_get_config_entry_diagnostics(
} }
) )
diagnostics_data = { return {
"config_entry_data": async_redact_data(dict(config_entry.data), TO_REDACT), "config_entry_data": async_redact_data(dict(config_entry.data), TO_REDACT),
"myuplink_data": async_redact_data(myuplink_data, TO_REDACT), "myuplink_data": async_redact_data(myuplink_data, TO_REDACT),
} }
return diagnostics_data

View File

@ -39,11 +39,7 @@ def get_description(device_point: DevicePoint) -> SwitchEntityDescription | None
2. Default to None 2. Default to None
""" """
prefix, _, _ = device_point.category.partition(" ") prefix, _, _ = device_point.category.partition(" ")
description = CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get( return CATEGORY_BASED_DESCRIPTIONS.get(prefix, {}).get(device_point.parameter_id)
device_point.parameter_id
)
return description
async def async_setup_entry( async def async_setup_entry(

View File

@ -22,9 +22,7 @@ async def async_get_config_entry_diagnostics(
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
coordinator: NAMDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id] coordinator: NAMDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
diagnostics_data = { return {
"info": async_redact_data(config_entry.data, TO_REDACT), "info": async_redact_data(config_entry.data, TO_REDACT),
"data": asdict(coordinator.data), "data": asdict(coordinator.data),
} }
return diagnostics_data

View File

@ -37,7 +37,7 @@ async def async_get_config_entry_diagnostics(
settings_coordinator = coordinators[ATTR_SETTINGS] settings_coordinator = coordinators[ATTR_SETTINGS]
status_coordinator = coordinators[ATTR_STATUS] status_coordinator = coordinators[ATTR_STATUS]
diagnostics_data = { return {
"config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT), "config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT),
"dnssec_coordinator_data": asdict(dnssec_coordinator.data), "dnssec_coordinator_data": asdict(dnssec_coordinator.data),
"encryption_coordinator_data": asdict(encryption_coordinator.data), "encryption_coordinator_data": asdict(encryption_coordinator.data),
@ -46,5 +46,3 @@ async def async_get_config_entry_diagnostics(
"settings_coordinator_data": asdict(settings_coordinator.data), "settings_coordinator_data": asdict(settings_coordinator.data),
"status_coordinator_data": asdict(status_coordinator.data), "status_coordinator_data": asdict(status_coordinator.data),
} }
return diagnostics_data

View File

@ -55,10 +55,9 @@ class NukiDoorsensorEntity(NukiEntity[NukiDevice], BinarySensorEntity):
@property @property
def extra_state_attributes(self): def extra_state_attributes(self):
"""Return the device specific state attributes.""" """Return the device specific state attributes."""
data = { return {
ATTR_NUKI_ID: self._nuki_device.nuki_id, ATTR_NUKI_ID: self._nuki_device.nuki_id,
} }
return data
@property @property
def available(self) -> bool: def available(self) -> bool:
@ -96,10 +95,9 @@ class NukiRingactionEntity(NukiEntity[NukiDevice], BinarySensorEntity):
@property @property
def extra_state_attributes(self): def extra_state_attributes(self):
"""Return the device specific state attributes.""" """Return the device specific state attributes."""
data = { return {
ATTR_NUKI_ID: self._nuki_device.nuki_id, ATTR_NUKI_ID: self._nuki_device.nuki_id,
} }
return data
@property @property
def is_on(self) -> bool: def is_on(self) -> bool:

View File

@ -116,8 +116,7 @@ class NumatoGpioAdc(SensorEntity):
def _clamp_to_source_range(self, val): def _clamp_to_source_range(self, val):
# clamp to source range # clamp to source range
val = max(val, self._src_range[0]) val = max(val, self._src_range[0])
val = min(val, self._src_range[1]) return min(val, self._src_range[1])
return val
def _linear_scale_to_dest_range(self, val): def _linear_scale_to_dest_range(self, val):
# linear scale to dest range # linear scale to dest range
@ -125,5 +124,4 @@ class NumatoGpioAdc(SensorEntity):
adc_val_rel = val - self._src_range[0] adc_val_rel = val - self._src_range[0]
ratio = float(adc_val_rel) / float(src_len) ratio = float(adc_val_rel) / float(src_len)
dst_len = self._dst_range[1] - self._dst_range[0] dst_len = self._dst_range[1] - self._dst_range[0]
dest_val = self._dst_range[0] + ratio * dst_len return self._dst_range[0] + ratio * dst_len
return dest_val

View File

@ -265,9 +265,7 @@ class PyNUTData:
manufacturer = _manufacturer_from_status(self._status) manufacturer = _manufacturer_from_status(self._status)
model = _model_from_status(self._status) model = _model_from_status(self._status)
firmware = _firmware_from_status(self._status) firmware = _firmware_from_status(self._status)
device_info = NUTDeviceInfo(manufacturer, model, firmware) return NUTDeviceInfo(manufacturer, model, firmware)
return device_info
async def _async_get_status(self) -> dict[str, str]: async def _async_get_status(self) -> dict[str, str]:
"""Get the ups status from NUT.""" """Get the ups status from NUT."""

View File

@ -69,9 +69,7 @@ class OmniLogicUpdateCoordinator(DataUpdateCoordinator[dict[tuple, dict[str, Any
return data return data
parsed_data = get_item_data(data, "Backyard", (), parsed_data) return get_item_data(data, "Backyard", (), parsed_data)
return parsed_data
class OmniLogicEntity(CoordinatorEntity[OmniLogicUpdateCoordinator]): class OmniLogicEntity(CoordinatorEntity[OmniLogicUpdateCoordinator]):

View File

@ -14,10 +14,9 @@ async def async_get_scanner(
) -> OPNSenseDeviceScanner: ) -> OPNSenseDeviceScanner:
"""Configure the OPNSense device_tracker.""" """Configure the OPNSense device_tracker."""
interface_client = hass.data[OPNSENSE_DATA]["interfaces"] interface_client = hass.data[OPNSENSE_DATA]["interfaces"]
scanner = OPNSenseDeviceScanner( return OPNSenseDeviceScanner(
interface_client, hass.data[OPNSENSE_DATA][CONF_TRACKER_INTERFACE] interface_client, hass.data[OPNSENSE_DATA][CONF_TRACKER_INTERFACE]
) )
return scanner
class OPNSenseDeviceScanner(DeviceScanner): class OPNSenseDeviceScanner(DeviceScanner):
@ -46,8 +45,7 @@ class OPNSenseDeviceScanner(DeviceScanner):
"""Return the name of the given device or None if we don't know.""" """Return the name of the given device or None if we don't know."""
if device not in self.last_results: if device not in self.last_results:
return None return None
hostname = self.last_results[device].get("hostname") or None return self.last_results[device].get("hostname") or None
return hostname
def update_info(self): def update_info(self):
"""Ensure the information from the OPNSense router is up to date. """Ensure the information from the OPNSense router is up to date.

View File

@ -368,12 +368,10 @@ class OverkizConfigFlow(ConfigFlow, domain=DOMAIN):
self, username: str, password: str, server: OverkizServer self, username: str, password: str, server: OverkizServer
) -> OverkizClient: ) -> OverkizClient:
session = async_create_clientsession(self.hass) session = async_create_clientsession(self.hass)
client = OverkizClient( return OverkizClient(
username=username, password=password, server=server, session=session username=username, password=password, server=server, session=session
) )
return client
async def _create_local_api_token( async def _create_local_api_token(
self, cloud_client: OverkizClient, host: str, verify_ssl: bool self, cloud_client: OverkizClient, host: str, verify_ssl: bool
) -> str: ) -> str:

View File

@ -234,8 +234,7 @@ class PlaatoCoordinator(DataUpdateCoordinator): # pylint: disable=hass-enforce-
async def _async_update_data(self): async def _async_update_data(self):
"""Update data via library.""" """Update data via library."""
data = await self.api.get_data( return await self.api.get_data(
session=aiohttp_client.async_get_clientsession(self.hass), session=aiohttp_client.async_get_clientsession(self.hass),
device_type=self.device_type, device_type=self.device_type,
) )
return data

View File

@ -200,8 +200,7 @@ def create_coordinator_container_vm(
def poll_api() -> dict[str, Any] | None: def poll_api() -> dict[str, Any] | None:
"""Call the api.""" """Call the api."""
vm_status = call_api_container_vm(proxmox, node_name, vm_id, vm_type) return call_api_container_vm(proxmox, node_name, vm_id, vm_type)
return vm_status
vm_status = await hass.async_add_executor_job(poll_api) vm_status = await hass.async_add_executor_job(poll_api)

View File

@ -90,9 +90,7 @@ class QVRProCamera(Camera):
@property @property
def extra_state_attributes(self): def extra_state_attributes(self):
"""Get the state attributes.""" """Get the state attributes."""
attrs = {"qvr_guid": self.guid} return {"qvr_guid": self.guid}
return attrs
def camera_image( def camera_image(
self, width: int | None = None, height: int | None = None self, width: int | None = None, height: int | None = None

View File

@ -174,8 +174,7 @@ def _significant_states_stmt(
StateAttributes, States.attributes_id == StateAttributes.attributes_id StateAttributes, States.attributes_id == StateAttributes.attributes_id
) )
if not include_start_time_state or not run_start_ts: if not include_start_time_state or not run_start_ts:
stmt = stmt.order_by(States.metadata_id, States.last_updated_ts) return stmt.order_by(States.metadata_id, States.last_updated_ts)
return stmt
unioned_subquery = union_all( unioned_subquery = union_all(
_select_from_subquery( _select_from_subquery(
_get_start_time_state_stmt( _get_start_time_state_stmt(

View File

@ -349,8 +349,7 @@ def get_start_time() -> datetime:
now = dt_util.utcnow() now = dt_util.utcnow()
current_period_minutes = now.minute - now.minute % 5 current_period_minutes = now.minute - now.minute % 5
current_period = now.replace(minute=current_period_minutes, second=0, microsecond=0) current_period = now.replace(minute=current_period_minutes, second=0, microsecond=0)
last_period = current_period - timedelta(minutes=5) return current_period - timedelta(minutes=5)
return last_period
def _compile_hourly_statistics_summary_mean_stmt( def _compile_hourly_statistics_summary_mean_stmt(

View File

@ -97,9 +97,7 @@ async def discover(hass):
"""Connect and authenticate home assistant.""" """Connect and authenticate home assistant."""
hub = RoonHub(hass) hub = RoonHub(hass)
servers = await hub.discover() return await hub.discover()
return servers
async def authenticate(hass: HomeAssistant, host, port, servers): async def authenticate(hass: HomeAssistant, host, port, servers):

View File

@ -55,8 +55,7 @@ async def async_get_triggers(
_hass: HomeAssistant, device_id: str _hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]: ) -> list[dict[str, str]]:
"""List device triggers for device.""" """List device triggers for device."""
triggers = [async_get_turn_on_trigger(device_id)] return [async_get_turn_on_trigger(device_id)]
return triggers
async def async_attach_trigger( async def async_attach_trigger(

View File

@ -256,8 +256,7 @@ class Schedule(CollectionEntity):
@classmethod @classmethod
def from_storage(cls, config: ConfigType) -> Schedule: def from_storage(cls, config: ConfigType) -> Schedule:
"""Return entity instance initialized from storage.""" """Return entity instance initialized from storage."""
schedule = cls(config, editable=True) return cls(config, editable=True)
return schedule
@classmethod @classmethod
def from_yaml(cls, config: ConfigType) -> Schedule: def from_yaml(cls, config: ConfigType) -> Schedule:

View File

@ -311,8 +311,7 @@ class SensiboDeviceSensor(SensiboDeviceBaseEntity, SensorEntity):
@property @property
def native_value(self) -> StateType | datetime: def native_value(self) -> StateType | datetime:
"""Return value of sensor.""" """Return value of sensor."""
state = self.entity_description.value_fn(self.device_data) return self.entity_description.value_fn(self.device_data)
return state
@property @property
def extra_state_attributes(self) -> Mapping[str, Any] | None: def extra_state_attributes(self) -> Mapping[str, Any] | None:

Some files were not shown because too many files have changed in this diff Show More