ha-async-patterns

A guide to writing asynchronous Python for Home Assistant, a home-automation platform. It explains how to keep network and other slow operations from blocking Home Assistant's single-threaded event loop.

In plain words
What is it for?
Use it when building or fixing Home Assistant integrations that fetch data, call APIs, or handle other I/O. It covers async and await, coroutines, and wrapping synchronous libraries.
Why use it?
Blocking the event loop can freeze automations, the user interface, and device updates. This provides patterns for using asynchronous libraries or moving blocking code to an executor.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/l3digitalnet/claude-code-plugins/ha-async-patterns
Any agent
npx skills add L3DigitalNet/Claude-Code-Plugins --skill ha-async-patterns
Clone the repo
git clone --depth 1 https://github.com/L3DigitalNet/Claude-Code-Plugins

Made for: Claude Code, Codex.

Per session 50 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 900 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00050 $0.00900
Opus 5 $0.00025 $0.00450
Sonnet 5 $0.00010 $0.00180
Haiku 4.5 $0.00005 $0.00090

Measured 2d ago against content hash 6b3b2589ea7f, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

ha-async-patterns scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

response = requests.get(f"http://{self._host}/api", timeout=10)
plugins/home-assistant-dev/skills/ha-async-patterns/SKILL.md · 147 lines

How it starts

The opening of the file, as written. The whole thing — 147 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Async Python Patterns in Home Assistant

Home Assistant runs on a single-threaded asyncio event loop. All I/O must be non-blocking. Blocking the loop freezes automations, the UI, and entity updates.

Pattern 1: Async Libraries (Preferred)

import aiohttp

async def async_get_data(self) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(f"http://{self._host}/api") as response:
            response.raise_for_status()
            return await response.json()

Pattern 2: Wrapping Sync Libraries

When no async library exists:

import requests

async def async_get_data(self) -> dict:
    return await self.hass.async_add_executor_job(self._sync_get_data)

def _sync_get_data(self) -> dict:
    response = requests.get(f"http://{self._host}/api", timeout=10)
    response.raise_for_status()
    return response.json()

With arguments:

# Positional args after callable (forwarded positionally — async_add_executor_job
# cannot pass keyword args, so options like timeout/headers need functools.partial)
result = await hass.async_add_executor_job(requests.get, url)

# Keyword args with functools.partial
from functools import partial
result = await hass.async_add_executor_job(
    partial(requests.get, url, timeout=10, headers=headers)
)

Pattern 3: Callbacks vs Coroutines

from homeassistant.core import callback

# @callback = sync, runs on event loop, NO I/O allowed
@callback
def _handle_coordinator_update(self) -> None:
    self._attr_native_value = self.coordinator.data.get("value")
    self.async_write_ha_state()

# async = coroutine, CAN do I/O
async def async_turn_on(self, **kwargs) -> None:
    await self.coordinator.client.async_set_state(True)
    await self.coordinator.async_request_refresh()

Pattern 4: Timeouts

import asyncio

from homeassistant.helpers.update_coordinator import UpdateFailed

async def async_get_data(self) -> dict:
    try:
        async with asyncio.timeout(10):
            return await self.client.async_get_data()
    except TimeoutError:
        raise UpdateFailed("Request timed out")

Read the full file on GitHub · 147 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 147 lines · 50 tokens per session scan A 6b3b2589ea7f

Subscribe to this mod's changes

ha-async-patterns is a skill published in the GitHub repository L3DigitalNet/Claude-Code-Plugins (6 stars, last pushed 3d ago), licensed MIT. It adds 50 tokens to every session and 900 once invoked, about $0.0003 per session on Opus 5. A static security scan graded it A with 1 finding (makes network calls). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

bump-dependency

Bumps a Python package dependency across Home Assistant Core integrations, regenerates core requirement files, runs verification tests and prek lint, and prepares a pull request with proper release/compare links.

home-assistant/core · 42 tokens

agent-framework-azure-ai-py

Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.

sickn33/agentic-awesome-skills · 24 tokens

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use…

K-Dense-AI/scientific-agent-skills · 76 tokens

python-feature-lifecycle

Guidance for package and feature lifecycle in the Agent Framework Python codebase, including stage meanings, feature-stage decorators, feature enums, and how to move APIs from one stage to the next.

microsoft/agent-framework · 43 tokens

python-development

Coding standards, conventions, and patterns for developing Python code in the Agent Framework repository. Use this when writing or modifying Python source files in the python/ directory.

microsoft/agent-framework · 35 tokens

marimo-pair

Work inside the user's live marimo notebook from the code editor: run Python in the same kernel the user does, inspect live notebook state, and commit durable notebook changes through code mode. Use whenever you create, analyze, or improve the user's marimo notebook.

marimo-team/marimo · 57 tokens