Improve performance of dict merge code (#1097)

Co-authored-by: Teemu R. <tpr@iki.fi>
This commit is contained in:
J. Nick Koston
2024-08-14 16:33:54 -05:00
committed by GitHub
parent 633f57dcce
commit 4669e08605
3 changed files with 29 additions and 20 deletions

View File

@@ -14,7 +14,6 @@ http://www.apache.org/licenses/LICENSE-2.0
from __future__ import annotations
import collections.abc
import functools
import inspect
import logging
@@ -29,22 +28,12 @@ from ..feature import Feature
from ..module import Module
from ..modulemapping import ModuleMapping, ModuleName
from ..protocol import BaseProtocol
from .iotmodule import IotModule
from .iotmodule import IotModule, merge
from .modules import Emeter
_LOGGER = logging.getLogger(__name__)
def merge(d, u):
"""Update dict recursively."""
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = merge(d.get(k, {}), v)
else:
d[k] = v
return d
def requires_update(f):
"""Indicate that `update` should be called before accessing this method.""" # noqa: D202
if inspect.iscoroutinefunction(f):

View File

@@ -1,6 +1,5 @@
"""Base class for IOT module implementations."""
import collections
import logging
from ..exceptions import KasaException
@@ -9,15 +8,17 @@ from ..module import Module
_LOGGER = logging.getLogger(__name__)
# TODO: This is used for query constructing, check for a better place
def merge(d, u):
def _merge_dict(dest: dict, source: dict) -> dict:
"""Update dict recursively."""
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = merge(d.get(k, {}), v)
for k, v in source.items():
if k in dest and type(v) is dict: # noqa: E721 - only accepts `dict` type
_merge_dict(dest[k], v)
else:
d[k] = v
return d
dest[k] = v
return dest
merge = _merge_dict
class IotModule(Module):