From 3d3f4ac29356e93cc6d362da96d78c3cf3358907 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 21 Jan 2024 17:45:45 -1000 Subject: [PATCH] Avoid recreating persistent notification update function when subscribing (#108624) I recently came up with an idea to look for callback functions that get created over and over frequently by adding logging to homeassistant.core.callback when its called to decorate a function. This one happens a lot at runtime. --- .../persistent_notification/__init__.py | 32 +++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/homeassistant/components/persistent_notification/__init__.py b/homeassistant/components/persistent_notification/__init__.py index 9ecb91bdb7f..6d6fb7bfbd6 100644 --- a/homeassistant/components/persistent_notification/__init__.py +++ b/homeassistant/components/persistent_notification/__init__.py @@ -4,6 +4,7 @@ from __future__ import annotations from collections.abc import Callable, Mapping from datetime import datetime from enum import StrEnum +from functools import partial import logging from typing import Any, Final, TypedDict @@ -213,6 +214,21 @@ def websocket_get_notifications( ) +@callback +def _async_send_notification_update( + connection: websocket_api.ActiveConnection, + msg_id: int, + update_type: UpdateType, + notifications: dict[str, Notification], +) -> None: + """Send persistent_notification update.""" + connection.send_message( + websocket_api.event_message( + msg_id, {"type": update_type, "notifications": notifications} + ) + ) + + @callback @websocket_api.websocket_command( {vol.Required("type"): "persistent_notification/subscribe"} @@ -225,19 +241,9 @@ def websocket_subscribe_notifications( """Return a list of persistent_notifications.""" notifications = _async_get_or_create_notifications(hass) msg_id = msg["id"] - - @callback - def _async_send_notification_update( - update_type: UpdateType, notifications: dict[str, Notification] - ) -> None: - connection.send_message( - websocket_api.event_message( - msg["id"], {"type": update_type, "notifications": notifications} - ) - ) - + notify_func = partial(_async_send_notification_update, connection, msg_id) connection.subscriptions[msg_id] = async_dispatcher_connect( - hass, SIGNAL_PERSISTENT_NOTIFICATIONS_UPDATED, _async_send_notification_update + hass, SIGNAL_PERSISTENT_NOTIFICATIONS_UPDATED, notify_func ) connection.send_result(msg_id) - _async_send_notification_update(UpdateType.CURRENT, notifications) + notify_func(UpdateType.CURRENT, notifications)