Make cv.string return subclasses of str as is (#103916)

This commit is contained in:
Erik Montnemery 2023-12-04 20:36:16 +01:00 committed by GitHub
parent 516966db33
commit 35e2f591c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 1 deletions

View File

@ -99,6 +99,7 @@ from homeassistant.generated.countries import COUNTRIES
from homeassistant.generated.languages import LANGUAGES
from homeassistant.util import raise_if_invalid_path, slugify as util_slugify
import homeassistant.util.dt as dt_util
from homeassistant.util.yaml.objects import NodeStrClass
from . import script_variables as script_variables_helper, template as template_helper
@ -581,7 +582,11 @@ def string(value: Any) -> str:
raise vol.Invalid("string value is None")
# This is expected to be the most common case, so check it first.
if type(value) is str: # noqa: E721
if (
type(value) is str # noqa: E721
or type(value) is NodeStrClass # noqa: E721
or isinstance(value, str)
):
return value
if isinstance(value, template_helper.ResultWrapper):

View File

@ -539,6 +539,13 @@ def test_string(hass: HomeAssistant) -> None:
for value in (True, 1, "hello"):
schema(value)
# Test subclasses of str are returned
class MyString(str):
pass
my_string = MyString("hello")
assert schema(my_string) is my_string
# Test template support
for text, native in (
("[1, 2]", [1, 2]),