diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index c82254bdcb1..6077e4708d5 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -733,17 +733,6 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_): return value - def __repr__(self) -> str: - """Return the representation. - - Entity.__repr__ includes the state in the generated string, this fails if we're - called before self.hass is set. - """ - if not self.hass: - return f"" - - return super().__repr__() - def _suggested_precision_or_none(self) -> int | None: """Return suggested display precision, or None if not set.""" assert self.registry_entry diff --git a/homeassistant/helpers/entity.py b/homeassistant/helpers/entity.py index fc627f51acf..b7ed7e3c095 100644 --- a/homeassistant/helpers/entity.py +++ b/homeassistant/helpers/entity.py @@ -1476,7 +1476,12 @@ class Entity( self.async_on_remove(self._async_unsubscribe_device_updates) def __repr__(self) -> str: - """Return the representation.""" + """Return the representation. + + If the entity is not added to a platform it's not safe to call _stringify_state. + """ + if self._platform_state != EntityPlatformState.ADDED: + return f"" return f"" async def async_request_call(self, coro: Coroutine[Any, Any, _T]) -> _T: diff --git a/tests/helpers/test_entity.py b/tests/helpers/test_entity.py index b85c8794fed..a74ef166907 100644 --- a/tests/helpers/test_entity.py +++ b/tests/helpers/test_entity.py @@ -1392,8 +1392,8 @@ async def test_translation_key(hass: HomeAssistant) -> None: assert mock_entity2.translation_key == "from_entity_description" -async def test_repr_using_stringify_state() -> None: - """Test that repr uses stringify state.""" +async def test_repr(hass) -> None: + """Test Entity.__repr__.""" class MyEntity(MockEntity): """Mock entity.""" @@ -1403,9 +1403,20 @@ async def test_repr_using_stringify_state() -> None: """Return the state.""" raise ValueError("Boom") + platform = MockEntityPlatform(hass, domain="hello") my_entity = MyEntity(entity_id="test.test", available=False) + + # Not yet added + assert str(my_entity) == "" + + # Added + await platform.async_add_entities([my_entity]) assert str(my_entity) == "" + # Removed + await platform.async_remove_entity(my_entity.entity_id) + assert str(my_entity) == "" + async def test_warn_using_async_update_ha_state( hass: HomeAssistant, caplog: pytest.LogCaptureFixture