Repository: home-assistant/core
File: homeassistant/components/zwave_js/lock.py (Python)

Code before:
    async def async_lock(self, **kwargs: Any) -> None:
        """Lock the lock."""
        await self._set_lock_state(LockState.LOCKED)

    async def async_unlock(self, **kwargs: Any) -> None:
        """Unlock the lock."""
        await self._set_lock_state(LockState.UNLOCKED)

    async def async_set_lock_usercode(self, code_slot: int, usercode: str) -> None:
        """Set the usercode to index X on the lock."""
        try:
            await set_usercode(self.info.node, code_slot, usercode)
        except BaseZwaveJSServerError as err:
            raise HomeAssistantError(
                f"Unable to set lock usercode on lock {self.entity_id} code_slot "
                f"{code_slot}: {err}"
            ) from err
        LOGGER.debug("User code at slot %s on lock %s set", code_slot, self.entity_id)

    async def async_get_lock_usercode(
        self, code_slot: int | None = None, refresh: bool = False
    ) -> ServiceResponse:
        """Get the usercode at index X on the lock."""
        if code_slot is None and refresh:
            raise ServiceValidationError(
                "The refresh option is only supported when querying a single code slot"
            )
        if code_slot is not None:
            return await self._async_get_single_usercode(code_slot, refresh)
        return await self._async_get_all_usercodes()

    async def _async_get_single_usercode(
        self, code_slot: int, refresh: bool
    ) -> ServiceResponse:
        """Get the usercode at index X on the lock."""
        try:
            if refresh:
                slot = await get_usercode_from_node(self.info.node, code_slot)
            else:
                slot = get_usercode(self.info.node, code_slot)
        except BaseZwaveJSServerError as err:
            raise HomeAssistantError(
                f"Unable to get lock usercode on lock {self.entity_id} code_slot "
                f"{code_slot}: {err}"
            ) from err
        return {
            str(code_slot): {
                "usercode": slot["usercode"],
                "in_use": slot["in_use"],
            },
        }

Review comment (suggestion):
It's nice to support translations of the error message:

https://developers.home-assistant.io/docs/internationalization/core/#exceptions

Code after:

    async def async_get_lock_usercode(
        self, code_slot: int | None = None
    ) -> ServiceResponse:
        """Get the usercode at index X on the lock."""
        if code_slot is not None:
            return self._get_single_usercode(code_slot)
        return self._get_all_usercodes()

    @callback
    def _get_single_usercode(self, code_slot: int) -> ServiceResponse:
        """Get the usercode at index X on the lock."""
        try:
            slot = get_usercode(self.info.node, code_slot)
        except NotFoundError as err:
            raise HomeAssistantError(
                translation_domain=DOMAIN,
                translation_key="get_lock_usercode_not_found",
                translation_placeholders={
                    "code_slot": str(code_slot),
                    "entity_id": self.entity_id,
                },
            ) from err
        return {
            str(code_slot): {
                "usercode": slot["usercode"],
                "in_use": slot["in_use"],
            },
        }

    @callback
    def _get_all_usercodes(self) -> ServiceResponse:
        """Get all usercodes from the lock."""
        slots = get_usercodes(self.info.node)
        return {
            str(slot["code_slot"]): {
                "usercode": slot["usercode"],
                "in_use": slot["in_use"],
            }
            for slot in slots
        }

    async def async_clear_lock_usercode(self, code_slot: int) -> None:
        """Clear the usercode at index X on the lock."""
        try:
            await clear_usercode(self.info.node, code_slot)
        except BaseZwaveJSServerError as err:
            raise HomeAssistantError(
                f"Unable to clear lock usercode on lock {self.entity_id} code_slot "
                f"{code_slot}: {err}"
            ) from err