I am currently developing a custom component and facing an issue with defining and using services from a separate services.py
file. I am trying to adhere to a clean architecture by separating service definitions from the __init__.py
file. However, I’m encountering errors when trying to pass the hass
object to my service handler.
Here’s a simple example based on the developer documentation:
# __init__.py
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers.typing import ConfigType
DOMAIN = "expose_service_async"
_LOGGER = logging.getLogger(__name__)
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up an async service example component."""
@callback
def my_service(call: ServiceCall) -> None:
_LOGGER.info('Received data', call.data)
hass.services.async_register(DOMAIN, 'demo', my_service)
return True
I want to move the my_service
definition to a services.py
file but maintain access to both the hass
and call
objects. When I try to define the service function in services.py
and pass both (hass, call)
, I receive a TypeError
stating that a required positional argument ‘call’ is missing.
Can someone guide me on how to correctly pass the hass
object to a service function defined in a separate file without encountering errors? Are there specific patterns or practices in Home Assistant for handling this scenario?