Skip to content
Open
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
7 changes: 6 additions & 1 deletion pyrefly/lib/alt/class/dataclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,12 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
let init_method = if let Some((root_model_type, has_strict)) =
self.get_pydantic_root_model_type_via_mro(cls, metadata)
{
self.get_pydantic_root_model_init(cls, root_model_type, has_strict)
self.get_pydantic_root_model_init(
cls,
root_model_type,
has_strict,
dataclass.kws.strict,
)
} else if metadata.is_pydantic_model() {
// Pydantic models with RootModel fields need type expansion
let transform_type: &dyn Fn(Type) -> Type = &|ty: Type| {
Expand Down
34 changes: 29 additions & 5 deletions pyrefly/lib/alt/class/pydantic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,23 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
cls: &Class,
root_model_type: Type,
has_strict: bool,
model_strict: bool,
) -> ClassSynthesizedField {
let is_any_or_quantified =
root_model_type.is_any() || matches!(root_model_type, Type::Quantified(_));
let has_default = matches!(
self.get_dataclass_member(cls, &ROOT),
DataclassMember::Field(_, keywords) if keywords.default.is_some()
);
let (has_default, field_strict) = match self.get_dataclass_member(cls, &ROOT) {
DataclassMember::Field(_, keywords) => (keywords.default.is_some(), keywords.strict),
_ => (false, None),
};
let has_strict = if has_strict {
true
} else {
match field_strict {
Some(false) => false,
Some(true) => model_strict || Self::is_pydantic_root_leaf_type(&root_model_type),
None => model_strict,
}
};
let root_requiredness = if is_any_or_quantified || has_default {
Required::Optional(None)
} else {
Expand All @@ -173,6 +183,20 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
ClassSynthesizedField::new(ty)
}

fn is_pydantic_root_leaf_type(ty: &Type) -> bool {
let inner = match ty {
Type::Union(union) => {
let mut non_none = union.members.iter().filter(|m| !matches!(m, Type::None));
match (non_none.next(), non_none.next()) {
(Some(single), None) => single,
_ => return false,
}
}
other => other,
};
matches!(inner, Type::ClassType(cls) if cls.targs().as_slice().is_empty())
}

/// Synthesizes BaseModel's typed signature or exposes an inherited nonstandard implementation.
pub fn get_pydantic_model_construct(
&self,
Expand Down Expand Up @@ -248,7 +272,7 @@ impl<'ctx, 'answer, Ans: LookupAnswer> AnswersSolver<'ctx, 'answer, Ans> {
let tparam = tparams.iter().next()?;
let root_model_type = self.heap.mk_quantified(tparam.clone());
Some(
self.get_pydantic_root_model_init(cls, root_model_type, false)
self.get_pydantic_root_model_init(cls, root_model_type, false, false)
.inner
.ty(),
)
Expand Down
21 changes: 21 additions & 0 deletions pyrefly/lib/test/pydantic/root_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,24 @@ def serialize(d: InnerModelDict) -> OuterModel:
return OuterModel(data=d)
"#,
);

pydantic_testcase!(
test_root_model_config_strict,
r#"
from pydantic import ConfigDict, RootModel

class Text(RootModel[str]):
model_config = ConfigDict(strict=True)

class Text2(RootModel[str], strict=True): ...

class Child(Text): ...

class Lax(RootModel[str]): ...

Text(b"hello") # E: Argument `Literal[b'hello']` is not assignable to parameter `root` with type `str`
Text2(b"hello") # E: Argument `Literal[b'hello']` is not assignable to parameter `root` with type `str`
Child(b"hello") # E: Argument `Literal[b'hello']` is not assignable to parameter `root` with type `str`
Lax(b"hello")
"#,
);
90 changes: 90 additions & 0 deletions pyrefly/lib/test/pydantic/strictness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -681,3 +681,93 @@ reveal_type(Model1.__init__) # E: revealed type: (self: Model1, *, t: type[LaxI

"#,
);

pydantic_testcase!(
test_root_model_field_strict_overrides_config,
r#"
from pydantic import ConfigDict, Field, RootModel, StrictStr

class Model(RootModel[str]):
model_config = ConfigDict(strict=True)
root: str = Field(strict=False)

class Model1(RootModel[str]):
root: str = Field(strict=True)

class Model2(RootModel[str]):
root: str = Field(strict=False)

class Model3(Model2):
model_config = ConfigDict(strict=True)

class Model4(Model2):
model_config = ConfigDict(strict=True)
root: str

class Model5(RootModel[StrictStr]):
root: StrictStr = Field(strict=False)

Model(b"hello")
Model1(b"hello") # E: Argument `Literal[b'hello']` is not assignable to parameter `root` with type `str`
Model2(b"hello")
Model3(b"hello")
Model4(b"hello") # E: Argument `Literal[b'hello']` is not assignable to parameter `root` with type `str`
Model5(b"hello") # E: Argument `Literal[b'hello']` is not assignable to parameter `root` with type `str`
"#,
);

pydantic_testcase!(
test_root_model_field_strict_shallow_containers,
r#"
from pydantic import Field, RootModel

class IntList(RootModel[list[int]]):
root: list[int] = Field(strict=True)

class IntDict(RootModel[dict[str, int]]):
root: dict[str, int] = Field(strict=True)


IntList(["1"])
IntList((1,))
IntDict({"a": "1"})
"#,
);

pydantic_testcase!(
test_root_model_config_and_field_strict_deep,
r#"
from pydantic import ConfigDict, Field, RootModel

class DirectStrict(RootModel[list[int]]):
model_config = ConfigDict(strict=True)
root: list[int] = Field(strict=True)

class BaseStrict(RootModel[list[int]]):
model_config = ConfigDict(strict=True)

class InheritedStrict(BaseStrict):
root: list[int] = Field(strict=True)


DirectStrict(["1"]) # E: Argument `list[str]` is not assignable to parameter `root` with type `list[int]`
InheritedStrict(["1"]) # E: Argument `list[str]` is not assignable to parameter `root` with type `list[int]`
"#,
);

pydantic_testcase!(
test_root_model_field_strict_optional_unwrapping,
r#"
from typing import Optional
from pydantic import Field, RootModel

class OptionalList(RootModel[Optional[list[int]]]):
root: Optional[list[int]] = Field(strict=True)

class OptionalInt(RootModel[Optional[int]]):
root: Optional[int] = Field(strict=True)

OptionalList(["1"])
OptionalInt("1") # E: Argument `Literal['1']` is not assignable to parameter `root` with type `int | None`
"#,
);
Loading