[ty] Preserve overloads for overridden keywords in functools.partial #30563
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?
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?
Thanks!
谢谢你给的两个例子。我复现后改成逐个检查联合分支,也让已经排除的重载不再触发 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.
carljm
Klu5ure
Summary
fetch_stream = partial(fetch, stream=True)为stream预先设置了默认值True。调用fetch_stream()时,会使用默认值,返回类型为str。调用fetch_stream(stream=False)时,显式传入的False会覆盖默认值,返回类型则为int。此前,ty 在创建
fetch_stream时,就提前排除了stream=False对应的重载,导致第二种合法调用被误报为类型错误。这次修复调整了重载的处理时机:不再提前排除该重载,而是将其保留下来,等分析具体调用时,再根据调用者实际传入的参数判断返回类型。
Fixes astral-sh/ty#5025