8000 Always convert str subclasses to str by adriangb · Pull Request #788 · pydantic/pydantic-core · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Always convert str subclasses to str #788

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/input/input_python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,12 @@ impl<'a> Input<'a> for PyAny {
}

fn strict_str(&'a self) -> ValResult<EitherString<'a>> {
if let Ok(py_str) = <PyString as PyTryFrom>::try_from(self) {
if let Ok(py_str) = <PyString as PyTryFrom>::try_from_exact(self) {
Ok(py_str.into())
} else if let Ok(py_str) = self.downcast::<PyString>() {
// force to a rust string to make sure behavior is consistent whether or not we go via a
// rust string in StrConstrainedValidator - e.g. to_lower
Ok(py_string_str(py_str)?.into())
} else {
Err(ValError::new(ErrorType::StringType, self))
}
Expand Down
18 changes: 18 additions & 0 deletions tests/validators/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,21 @@ def test_lax_subclass(FruitEnum, kwargs):
assert p == 'pear'
assert type(p) is str
assert repr(p) == "'pear'"


def test_subclass_preserved() -> None:
class StrSubclass(str):
pass

v = SchemaValidator(core_schema.str_schema())

assert not isinstance(v.validate_python(StrSubclass('')), StrSubclass)
assert not isinstance(v.validate_python(StrSubclass(''), strict=True), StrSubclass)

# unions do a first pass in strict mode
# so verify that they don't match the str schema in strict mode
# and preserve the type
v = SchemaValidator(core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()]))

assert not isinstance(v.validate_python(StrSubclass('')), StrSubclass)
assert not isinstance(v.validate_python(StrSubclass(''), strict=True), StrSubclass)
0