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
19 changes: 18 additions & 1 deletion pyrefly/lib/alt/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,9 +839,26 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> {
FunctionParameter::Annotated(idx) => {
// If the parameter is annotated, we check the default value against the annotation
let param_ty = self.get_idx(*idx).annotation.get_type().clone();
// For parameter default validation, substitute TypeVars that have
// defaults with their default types. This allows `def f[S=None](x: S = None)`
// to pass: the check becomes `None <: None` instead of `None <: S`.
let check_ty;
let check_ref = if default.is_some() {
check_ty = param_ty.clone().transform(&mut |t| {
if let Type::Quantified(q) = &*t
&& q.default().is_some()
{
let gradual = q.as_gradual_type();
*t = gradual;
}
});
&check_ty
} else {
&param_ty
};
let required = self.get_requiredness(
default,
Some((&param_ty, &|| {
Some((check_ref, &|| {
TypeCheckContext::of_kind(TypeCheckKind::FunctionParameterDefault(
name.id.clone(),
))
Expand Down
44 changes: 44 additions & 0 deletions pyrefly/lib/test/generic_restrictions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,50 @@ assert_type(f(1), int | str)
"#,
);

// Issue #2711: TypeVar defaults in function parameter defaults
testcase!(
test_typevar_default_param_default,
r#"
from typing import assert_type, reveal_type
class Getter[T]:
def get[S=None](self, default: S = None) -> T | S: ...

def test(arg: Getter[str]) -> None:
reveal_type(arg.get()) # E: revealed type: str | None
assert_type(arg.get(), str | None)
"#,
);

testcase!(
test_typevar_default_param_default_no_infer_with_first_use,
TestEnv::new_with_infer_with_first_use(false),
r#"
from typing import assert_type, reveal_type
class Getter[T]:
def get[S=None](self, default: S = None) -> T | S: ...

def test(arg: Getter[str]) -> None:
reveal_type(arg.get()) # E: revealed type: str | None
assert_type(arg.get(), str | None)
"#,
);

testcase!(
test_typevar_default_param_default_mismatch,
r#"
def f[S=int](x: S = "hello") -> S: ... # E: Default `Literal['hello']` is not assignable to parameter `x`
"#,
);

testcase!(
test_function_no_typevar_default_unchanged,
r#"
from typing import assert_type
def f[T](x: T) -> T: ...
assert_type(f(1), int)
"#,
);

testcase!(
test_unsolved_typevar_with_constraints,
r#"
Expand Down
Loading