← Back to Pull requests

[ty] Preserve overloads for overridden keywords in functools.partial #30563

Open
Klu5ure opened this pull request with 261 lines diff across 2 files
View on GitHub
Klu5ure Klu5ure commented on Nov 19, 2026 06:31 UTC
Author

Summary

fetch_stream = partial(fetch, stream=True) 为 stream 预先设置了默认值 True。调用 fetch_stream() 时,会使用默认值,返回类型为 str。调用 fetch_stream(stream=False) 时,显式传入的 False 会覆盖默认值,返回类型则为 int。

此前,ty 在创建 fetch_stream 时,就提前排除了 stream=False 对应的重载,导致第二种合法调用被误报为类型错误。

这次修复调整了重载的处理时机:不再提前排除该重载,而是将其保留下来,等分析具体调用时,再根据调用者实际传入的参数判断返回类型。

fetch_stream = partial(fetch, stream=True) sets stream to True by default. Calling fetch_stream() uses that default and returns str. Calling fetch_stream(stream=False) overrides the default and returns int.

> Previously, ty ruled out the stream=False overload when it created fetch_stream, so it reported a type error for the second call.

> With this change, ty keeps an overload if overriding a stored keyword argument can make it match. It can then infer the return type from the arguments supplied at the call site.

Fixes astral-sh/ty#5025

Diff: 261 lines (+192 / -69) across 2 files Reviewer: carljm Review duration: 22712m
All Vouch review confidence checks passed
Residual risk 0.03 = Change Risk (0.38) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.38 · 261 lines diff across 2 files
0.38
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.94 · 3 substantive comment(s)
0.94
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
90%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.333
Real PR Conversation Timeline
5 items
carljm carljm commented on code on Nov 20, 2026 01:52 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -3807,35 +3803,41 @@ impl<'db> CallableBinding<'db> {
             if self.overloads().len() > 1 {
                 return None;
             }
-
-            selected_overload_indexes.push(source_overload_index);
         }
 
+        let cases = self.partial_keyword_cases();
         let signature_arguments = bound_call_arguments.with_self(self.bound_type);
-        let signatures: SmallVec<[(usize, Signature<'db>); 1]> = selected_overload_indexes
-            .into_iter()
-            .map(|index| {
-                let overload = &self.overloads()[index];
-                // TODO: Preserve intersected parameter lists when synthesizing partial signatures.
-                if let Some((_, paramspec)) =
-                    overload.signature.parameters().as_paramspec_with_prefix()
-                    && let Some(value) = overload
-                        .merged_specialization(db)
-                        .and_then(|specialization| specialization.get(db, paramspec))
-                    && matches!(
-                        value.as_paramspec_value(db),
-                        Some(ParamSpecValue::Intersection(_))
-                    )
-                {
-                    return None;
-                }
-                Some((
-                    index,
-                    overload.partially_applied_signature(db, env, signature_arguments.as_ref()),
-                ))
-            })
-            .collect::<Option<_>>()?;
-        if let Some(cases) = self.partial_keyword_cases() {
+        let mut signatures = SmallVec::<[(usize, Signature<'db>); 1]>::new();
+        for (index, overload) in self.overloads.iter().enumerate() {
+            // TODO: Preserve intersected parameter lists when synthesizing partial signatures.
+            if let Some((_, paramspec)) = overload.signature.parameters().as_paramspec_with_prefix()
+                && let Some(value) = overload
+                    .merged_specialization(db)
+                    .and_then(|specialization| specialization.get(db, paramspec))
+                && matches!(
+                    value.as_paramspec_value(db),
+                    Some(ParamSpecValue::Intersection(_))
+                )
+            {
+                return None;
+            }
+            let mut signature =
+                overload.partially_applied_signature(db, env, signature_arguments.as_ref());
+            // Expanded calls check overrides against each case's own binding errors below.
+            if cases.is_none() && self.overloads.len() > 1 && !compatible(overload) {
+                let Some(required) = require_keyword_overrides(
+                    db,
+                    bound_call_arguments,
+                    signature,
+                    &overload.errors,

Reversing the order of the union members in the positional argument changes whether we accept y=None here.

from functools import partial
from typing import overload

@overload
def f(x: int, y: int) -> None: ...
@overload
def f(x: str, y: int) -> None: ...
@overload
def f(x: int, y: None) -> None: ...
def f(x, y): ...

def check(a: int | str, b: str | int):
    partial(f, a, y=0)(y=None)  # accepted
    partial(f, b, y=0)(y=None)  # rejected

I’d expect both calls to get an error, as they do on main, since y=None requires x to be an int. Only x expands here, so cases is None. The third overload fails for both members at construction, so its merged errors are just those for the first member (y for int, both x and y for str). Could we check each expansion before deciding that overriding y is enough?

carljm carljm commented on code on Nov 20, 2026 01:52 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -3807,35 +3803,41 @@ impl<'db> CallableBinding<'db> {
             if self.overloads().len() > 1 {
                 return None;
             }
-
-            selected_overload_indexes.push(source_overload_index);
         }
 
+        let cases = self.partial_keyword_cases();
         let signature_arguments = bound_call_arguments.with_self(self.bound_type);
-        let signatures: SmallVec<[(usize, Signature<'db>); 1]> = selected_overload_indexes
-            .into_iter()
-            .map(|index| {
-                let overload = &self.overloads()[index];
-                // TODO: Preserve intersected parameter lists when synthesizing partial signatures.
-                if let Some((_, paramspec)) =
-                    overload.signature.parameters().as_paramspec_with_prefix()
-                    && let Some(value) = overload
-                        .merged_specialization(db)
-                        .and_then(|specialization| specialization.get(db, paramspec))
-                    && matches!(
-                        value.as_paramspec_value(db),
-                        Some(ParamSpecValue::Intersection(_))
-                    )
-                {
-                    return None;
-                }
-                Some((
-                    index,
-                    overload.partially_applied_signature(db, env, signature_arguments.as_ref()),
-                ))
-            })
-            .collect::<Option<_>>()?;
-        if let Some(cases) = self.partial_keyword_cases() {
+        let mut signatures = SmallVec::<[(usize, Signature<'db>); 1]>::new();
+        for (index, overload) in self.overloads.iter().enumerate() {
+            // TODO: Preserve intersected parameter lists when synthesizing partial signatures.
+            if let Some((_, paramspec)) = overload.signature.parameters().as_paramspec_with_prefix()
+                && let Some(value) = overload
+                    .merged_specialization(db)
+                    .and_then(|specialization| specialization.get(db, paramspec))
+                && matches!(
+                    value.as_paramspec_value(db),
+                    Some(ParamSpecValue::Intersection(_))
+                )
+            {
+                return None;

This fallback can erase the signature of a partial that only binds positional arguments.

from functools import partial
from typing import Callable, overload, reveal_type

type Consumer[**P] = Callable[[Callable[P, None]], None]

@overload
def f[**P](x: int, cb: Consumer[P], /, *args: P.args, **kwargs: P.kwargs) -> int: ...
@overload
def f(x: str, cb: object, /) -> str: ...
def f(x, cb, /, *args, **kwargs):
    return x

def check(cb: Consumer[[int]] | Consumer[[str]]):
    p = partial(f, "", cb)
    reveal_type(p)  # partial[() -> str] on main, partial[Unknown] here
    p(None)  # rejected on main, accepted here

The "" argument rules out the first overload for every call to p. We hit return None for its intersected ParamSpec before checking that mismatch. Could we restrict this fallback to overloads that survive filtering?

carljm carljm requested changes on Nov 20, 2026 01:57 UTC
Changes Requested Reviewer

Thanks!

Klu5ure Klu5ure commented on Nov 21, 2026 17:24 UTC
Author

谢谢你给的两个例子。我复现后改成逐个检查联合分支,也让已经排除的重载不再触发 ParamSpec 回退。两个例子都加了回归测试,本地 524 个 Markdown 测试通过。

AI translation

Thanks for the two examples! I reproduced both issues. Keyword overrides are now checked separately for each expanded argument list, and overloads that have been ruled out no longer trigger the ParamSpec fallback. I added regression tests for both examples, and all 524 ty_python_semantic Markdown tests passed locally.

Reviewers
Assignees
Klu5ure Klu5ure
Labels
risk: low confidence: 91.0% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 37.8% (MEDIUM) · Higher = larger blast radius
37.8%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 91.0% · Lower = rushed or shallow review
91.0%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 3.4% · Safe to merge
3.4%
Repository