mirror of
https://github.com/astral-sh/ruff.git
synced 2026-12-04 02:03:58 +08:00
[ty] Skip overload prefix checks for literal parameters (#31043)
## Summary When the service name is `Any`, we check whether some prefix of the overloads accepts every possible value. A prefix that only accepts literal service names can never cover `object()`. We already use that observation to skip prefix checks for some parameter types. We now recognize literal types here too, including unions where every member excludes `object()`. Checking `boto3auth` with `boto3-stubs` was 7.7% faster on a single worker (112 ms to 104 ms, faster in 17 of 18 paired runs). In `boto3-stubs` 1.44.3, all 435 overloads of `Session.client` take a literal service name.
This commit is contained in:
@@ -1641,6 +1641,35 @@ def _(value: Any):
|
||||
reveal_type(select(value)) # revealed: str
|
||||
```
|
||||
|
||||
### Literal parameters and an argument of type `Any`
|
||||
|
||||
No union of service names covers every value of `Any`. The fallback overload still contributes to
|
||||
the result when the name is dynamic.
|
||||
|
||||
`overloaded.pyi`:
|
||||
|
||||
```pyi
|
||||
from typing import Literal, overload
|
||||
|
||||
@overload
|
||||
def client(name: Literal["storage"]) -> int: ...
|
||||
@overload
|
||||
def client(name: Literal["logs", "metrics"]) -> int: ...
|
||||
@overload
|
||||
def client(name: object) -> str: ...
|
||||
```
|
||||
|
||||
```py
|
||||
from typing import Any
|
||||
from overloaded import client
|
||||
|
||||
def _(name: Any):
|
||||
reveal_type(client(name)) # revealed: Unknown
|
||||
|
||||
reveal_type(client("storage")) # revealed: int
|
||||
reveal_type(client("other")) # revealed: str
|
||||
```
|
||||
|
||||
### Single list argument
|
||||
|
||||
`overloaded.pyi`:
|
||||
|
||||
@@ -3607,6 +3607,7 @@ impl<'db> OverloadFilterCandidate<'db> {
|
||||
return false;
|
||||
};
|
||||
let excludes_object = |ty| match ty {
|
||||
Type::LiteralValue(_) => true,
|
||||
Type::NominalInstance(instance) => !instance.is_object(),
|
||||
Type::ProtocolInstance(protocol) => {
|
||||
!has_all_protocol_members_defined(db, env, Type::object(), protocol)
|
||||
|
||||
Reference in New Issue
Block a user