Skip to content

Commit

Permalink
Fix unintended create call.
Browse files Browse the repository at this point in the history
Second attribute of `setdefault` is always evaluated, causing unintended calls to create device entry on each recieved frame, instead of only once.
  • Loading branch information
denpamusic committed May 9, 2024
1 parent 7403f04 commit e263ff9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
15 changes: 10 additions & 5 deletions pyplumio/helpers/factory.py
Expand Up @@ -2,21 +2,26 @@
from __future__ import annotations

import asyncio
from importlib import import_module
import importlib
import logging
from types import ModuleType
from typing import Any

_LOGGER = logging.getLogger(__name__)


async def _load_module(module_name: str) -> ModuleType:
"""Load a module by name."""
return await asyncio.get_running_loop().run_in_executor(
None, importlib.import_module, f".{module_name}", "pyplumio"
)


async def create_instance(class_path: str, **kwargs: Any) -> Any:
"""Return a class instance from the class path."""
loop = asyncio.get_running_loop()
module_name, class_name = class_path.rsplit(".", 1)
try:
module = await loop.run_in_executor(
None, import_module, "." + module_name, "pyplumio"
)
module = await _load_module(module_name)
return getattr(module, class_name)(**kwargs)
except Exception:
_LOGGER.error("Failed to load module (%s)", class_path)
Expand Down
7 changes: 4 additions & 3 deletions pyplumio/protocol.py
Expand Up @@ -233,9 +233,10 @@ async def frame_consumer(self, read_queue: asyncio.Queue) -> None:
async def get_device_entry(self, device_type: DeviceType) -> AddressableDevice:
"""Set up device entry."""
handler, name = get_device_handler_and_name(device_type)
return self.data.setdefault(
name, await self._create_device_entry(name, handler)
)
if name not in self.data:
self.data[name] = await self._create_device_entry(name, handler)

return self.data[name]

async def _create_device_entry(self, name: str, handler: str) -> AddressableDevice:
"""Create device entry."""
Expand Down

0 comments on commit e263ff9

Please sign in to comment.