diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 1786194b437..9f8eb628e63 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -507,10 +507,26 @@ class Template: ) def __init__(self, template: str, hass: HomeAssistant | None = None) -> None: - """Instantiate a template.""" + """Instantiate a template. + + Note: A valid hass instance should always be passed in. The hass parameter + will be non optional in Home Assistant Core 2025.10. + """ + # pylint: disable-next=import-outside-toplevel + from .frame import report + if not isinstance(template, str): raise TypeError("Expected template to be a string") + if not hass: + report( + ( + "creates a template object without passing hass, " + "which will stop working in HA Core 2025.10" + ), + error_if_core=False, + ) + self.template: str = template.strip() self._compiled_code: CodeType | None = None self._compiled: jinja2.Template | None = None diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index e4f833b2d1d..339b372f137 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -6547,3 +6547,20 @@ async def test_merge_response_with_incorrect_response(hass: HomeAssistant) -> No tpl = template.Template(_template, hass) with pytest.raises(TemplateError, match="TypeError: Response is not a dictionary"): tpl.async_render() + + +def test_warn_no_hass(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -> None: + """Test deprecation warning when instantiating Template without hass.""" + + message = "Detected code that creates a template object without passing hass" + template.Template("blah") + assert message in caplog.text + caplog.clear() + + template.Template("blah", None) + assert message in caplog.text + caplog.clear() + + template.Template("blah", hass) + assert message not in caplog.text + caplog.clear()