## Summary
This PR splits `mismatched-type-name` into eight independently
configurable warnings for `NewType`, functional enums, `TypeVar`,
`ParamSpec`, `TypeVarTuple`, `namedtuple`/`NamedTuple`, `TypedDict`, and
`TypeAliasType`.
~~This PR is actually quite a bit less breaking for users than other
rule splits we've done over the last few days. Because
`mismatched-type-name` is no longer the canonical name for _any_ rule on
this branch, we're able to make it a deprecated alias for _all_ the new
rules, meaning that it will continue to work on the CLI, in ty
configuration files, and ty suppression comments (we'll just emit a
warning diagnostic telling users to upgrade their configuration
file/suppression comment).~~
~~A more specific rule takes precedence over the deprecated name if both
are given within the same configuration table. On the command line, the
last matching flag wins (e.g. `--error=mismatched-enum-name
--ignore=mismatched-type-name` will suppress diagnostics for mismatched
enum names).~~
(After review from @MichaReiser, I backed out these changes. It's now a
somewhat breaking change, because the rule is now marked as "removed"
rather than "deprecated".)
As well as splitting the rule into eight separate rules, it also cleans
up our error recovery for several of these type factories. For example,
in the following snippet, we fail to recognize `T` as a `TypeVar` due to
bad error recovery from the non-literal name. But we don't really need a
nonliteral name in this case to determine that it's a validly
constructed TypeVar. It's probably a mistake, but there's no _soundness_
issue here:
```py
from typing import TypeVar
def f(x: str):
# main emits an error: `invalid-typevar`
# this PR emits a warning: `mismatched-typevar-name`
T = TypeVar(x)
def g(x: T) -> T:
return x
reveal_type(g(42)) # main: Todo. This PR: `Literal[42]`.
```
## Motivation
The main motivation here is that having a namedtuple or enum with the
"wrong name", for example, just seems much less "obviously wrong" than
having a typevar or paramspec with the "wrong name". The [ecosystem
report](https://github.com/astral-sh/ruff/pull/29957#issuecomment-6603964612)
is evidence of this. namedtuples and enums define runtime classes that
can be used in runtime contexts and instantiated; these constructs
aren't _just_ for type checkers.
TypeVars/ParamSpecs/TypeVarTuples/NewTypes/TypedDicts are all _only_ for
type checkers and there's no plausible reason why you'd want to give the
type a different name to the variable it's assigned to.
`mismatched-namedtuple-name` and `mismatched-enum-name` are therefore
now disabled by default, matching the default severity we already
settled on for `mistmatched-sentinel-name` in
https://github.com/astral-sh/ruff/pull/27206. `mismatched-typevar-name`,
`mismatched-paramspec-name`, `mismatched-typevartuple-name`,
`mismatched-enum-name`, `mismatched-namedtuple-name` and
`mismatched-newtype-name` all remain enabled by default with `warning`
severity.
## Summary
We split out a new `lost-keyword-for-regular-parameter` rule for a
special case of `incompatible-method-override` where the overriding
method drops a keyword parameter (renames it, or makes it
positional-only). This is how the new diagnostic looks like:
```python
class Base:
def scale(self, factor: int) -> int:
return factor * 2
class Wrong(Base):
def scale(self, multiplier: int) -> int:
return multiplier * 3
```
```text
error[lost-keyword-for-regular-parameter]: Override of method `scale` disallows keyword arguments allowed by the method on the base class
--> example.py:7:9
|
7 | def scale(self, multiplier: int) -> int:
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Definition is incompatible with `Base.scale`
|
::: example.py:2:9
|
2 | def scale(self, factor: int) -> int:
| ------------------------------- `Base.scale` defined here
info: the parameter named `multiplier` does not match `factor` (and can be used as a keyword parameter)
info: This violates the Liskov Substitution Principle
Found 1 diagnostic
```
## Test strategy
New Markdown tests
<details>
<summary>Ecosystem impact</summary>
Across 165 projects, 1,946 existing errors moved from
`incompatible-method-override` to the new rule at the same locations and
severity. The linked run used the previous name,
`missing-keyword-in-override`.
The split surfaced 65 previously suppressed errors. Sphinx (28), Kornia
(25), and Altair (2) disable the old rule in configuration. The other 10
errors appeared at inline suppressions in pip, Streamlit, scipy-stubs,
and pandas-stubs. Seven of those comments also triggered
`unused-ignore-comment`.
The run reported no timeouts or abnormal exits and an average timing
factor of 1.00×.
</details>
---------
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
Rename the method, attribute, property, and mutable override rules to
`incompatible-…-override`. The old names remain aliases in configuration
and inline suppressions:
| Before | After |
|---|---|
| `invalid-method-override` | `incompatible-method-override` |
| `invalid-attribute-override` | `incompatible-attribute-override` |
| `invalid-property-type-override` | `incompatible-property-override` |
| `invalid-mutable-override` | `incompatible-mutable-override` |
A follow-up PR will split `invalid-method-override` into two rules.
Fixesastral-sh/ty#2001.
---------
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
## Summary
Users can now suppress an attribute error that affects only some union
members and still catch names that are missing from every member. For
example, both lines below previously reported `unresolved-attribute`:
```python
def clean(value: str | int) -> str:
value.stirp() # missing-attribute: neither str nor int has stirp
return value.strip() # missing-union-attribute: str has strip, int does not
```
The motivation is that a project adopting ty may want `value.strip()` on
`str | None` to only warn while a typo remains an error-severity
diagnostic.
Both rules default to errors. The same distinction applies to optional
values such as `str | None` and to attribute deletion. Attributes
defined only conditionally on a class continue to use
`possibly-missing-attribute`.
### Comparison to other type checkers
Pyright distinguishes between `reportOptionalMemberAccess` (which is
specifically for unions with `None`) and `reportAttributeAccessIssue`,
which is for all other unions. mypy, meanwhile, distinguishes between
`union-attr` (which is an error code for all attribute-access errors on
union types) and `attr-defined` (which is an error code for all
attribute-access errors on non-union types). So this new split doesn't
_exactly_ align with either precedent -- but I _do_ think it's probably
the most useful split we can do, and it's the one that makes the most
sense _a priori_ in my opinion.
### Compatibility
`unresolved-attribute` remains an alias for `missing-attribute` in
configuration and inline ignores. To preserve a setting such as
`unresolved-attribute = "warn"` for both cases, also set
`missing-union-attribute = "warn"`. On an access that fails for only
some union members, replace `# ty: ignore[unresolved-attribute]` with `#
ty: ignore[missing-union-attribute]`. Tools that consume diagnostic
codes should recognize both new names.
Fixesastral-sh/ty#2839 and fixesastral-sh/ty#2471.
## Test Plan
A comparison with ty 0.0.96 on typeshed-stats, docstring-adder,
sphinx-lint, and typing_extensions found the same messages, locations,
and severities. Eight diagnostics received `missing-union-attribute`
across those four projects (two in sphinx-lint and six in
typing_extensions).
---------
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
## Summary
With this PR, we now support the following scenario where a function on
a class is shadowed by an instance attribute:
```python
class C:
def method(self, x: int) -> str:
return str(x)
def some_compatible_method(self, x: int) -> str:
return str(x)
def swap(self) -> None:
self.method = self.some_compatible_method # previously an error
c = C()
c.swap()
c.method(42) # previously an error (two, actually)
```
(see [this
section](https://github.com/astral-sh/ruff/blob/078b001e5c09f9c301ee7d91092b4946d0591d63/crates/ty_python_semantic/resources/mdtest/call/methods.md#shadowing-methods)
for an in-depth description of what happens here)
Shadowing a method in this way is only sound in a small number of cases.
We deliberately relax conditions here to support various use cases that
came up in the ecosystem. We only require the shadowing callable
(`self.some_compatible_method` above) to be assignable to the
(generalized, regular) callable type of the original `method` after that
has been bound to the receiver in question (`self` here).
See the mdtests linked above for a broaded discussion of the unsoundness
that this introduces. We plan to add a new strict-mode diagnostic for
users who want to prevent those scenarios.
We implement this in the following way:
- When validating the assignment `self.method = ...`, we compare the
right-hand side callable with a "contract type" that is computed from
the bound-method type of the original method, which results in (`(x:
int) -> str`) for the example above. This allows the assignment above to
pass.
- During attribute lookup (`c.method`), we "hide" the implicit instance
attribute (this needs to be done in two places, unfortunately). This
means that `c.method` only sees the original function on the meta type
`C` (and no "fallback" on the instance). And so according to normal
descriptor protocol rules, this means that we simply get a bound method
object (`C.method` bound to `c`). This avoids confusing and problematic
union types that consist of (a) the bound method resulting from binding
the original function to the new receiver and (b) the bound method
referring to the `self` receiver which is stored on the instance. It
might also be a performance optimization.
fixesastral-sh/ty#350.
fixesastral-sh/ty#4823.
## Ecosystem
Looks good. A few exceptions:
- GraphQL-core: I documented this regression in an mdtest. See my inline
comment
- hydra-zen: This is a pre-existing limitation. I reported
https://github.com/astral-sh/ty/issues/4926
## Testing
Updated existing mdtests
## Summary
ty currently reports `unresolved-import` for both a missing module and a
missing member in a `from` import. But the word "unresolved" is heavily
overloaded in Python, and has been reported by users as being confusing
(see https://github.com/astral-sh/ty/issues/2471). This PR renames the
rule to `import-not-found`, which describes the lookup failure in either
case.
Configuration, command-line flags, and ignore comments accept either
spelling. If several flags set this rule’s severity using different
spellings, the last flag wins. Existing baseline entries still match,
and rewriting a baseline uses the new name. Links to the old rule
heading still work.
Builds on #29200.
When an invalid implicit alias is used as a type, the error now explains
why its original right-hand side is invalid and points to that
expression. For example:
```py
Called = type(1)
# snapshot: invalid-type-form
def inspect(called: Called):
reveal_type(called) # revealed: Unknown
```
```text
error[invalid-type-form]: Variable is not allowed in parameter annotations
--> src/mdtest_snippet.py:14:21
|
14 | def inspect(called: Called):
| ^^^^^^
info: Function calls are not allowed in type alias values
--> src/mdtest_snippet.py:11:10
|
11 | Called = type(1)
| ^^^^^^^
info: See the following page for a reference on valid type expressions:
info: https://typing.python.org/en/latest/spec/annotations.html#type-and-annotation-expressions
```
No other type checker provides this kind of detailed origin explanation
when a value is not usable as a type alias.
Follow imports and forwarding assignments to the original definition.
Collect these explanations independently of diagnostics in the defining
file, so unchecked dependencies and local suppressions do not hide them.
Ordinary assignments remain valid at runtime; the error is reported only
where the value is used as a type.
Unpacking a tuple with repeated incompatible element types into a
variadic parameter can emit identical `invalid-argument-type`
diagnostics at the same starred argument. Report each identical mismatch
once, while retaining distinct errors for different source arguments,
parameters, or expected and provided types.
Deduplicate when emitting diagnostics so all parameter matches, type
checks, and failing-overload error counts remain intact.
## Ecosystem report
For head `ed5e760595e57b6f83c6bd66e9dbdc80d149fcad`, the ecosystem
comparison removes three duplicate `invalid-argument-type` diagnostics:
two in Prefect and one in SymPy. Each affected call retains one error,
and distinct diagnostics remain unchanged. Exact-run reproduction and
minimized examples confirm the expected behavior; all readiness checks
passed.
[Full ecosystem
report](https://github.com/astral-sh/ruff/pull/29337#issuecomment-6152510514).
## Summary
Four links in the repo point at things that moved:
- `BREAKING_CHANGES.md` links `CHANGELOG.md#090` and `CHANGELOG.md#030`,
but those sections live in `changelogs/0.9.x.md` and
`changelogs/0.3.x.md` now, so on GitHub the links land at the top of
`CHANGELOG.md`.
- `invalid_argument_type.md` points at `invalid_assignment_details.md`,
which #24690 renamed to `error_context.md`.
- `generics/scoping.md` links `./call/methods.md`, which resolves inside
`generics/`; the file is `../call/methods.md`.
## Test Plan
Opened each new target on github.com. The `#090` and `#030` anchors
resolve on the changelog pages; the old ones on `CHANGELOG.md` don't.
I found these while trying Amiss (https://github.com/HardMax71/amiss), a
docs drift checker I'm building.
---------
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
## Summary
Add a new opt-in `truthiness-test-of-none-union ` rule which flags
truthiness checks on types like `int | None` or `str | None`. For
example, it will emit an error on the following (problematic) `if not
limit` check:
```py
def take(items: list[str], limit: int | None = None) -> list[str]:
if not limit: # error: [truthiness-test-of-none-union]
return items
return items[:limit]
```
Related to https://github.com/astral-sh/ruff/discussions/8757 and
inspired by Pyrefly's `implicit-bool` rule (but narrower in scope).
## Test strategy
New test suite
## Summary
Prior to this change, we treated imports as declarations, incorrectly
requiring later assignments to preserve the imported type:
```py
import os
from types import ModuleType
def normalize(module: ModuleType) -> ModuleType:
return module
os = normalize(os)
```
We now model regular imports, `from` imports, and wildcard imports as
bindings rather than declarations. This allows ordinary reassignment,
context-manager targets, and optional-import fallbacks while preserving
existing local annotations.
Imported `Final` qualifiers are tracked separately from declared types
through use-def flow. This preserves the qualifier across assignments,
re-exports, and branches without replacing explicit annotations or
treating imports as protocol-member declarations. The implementation
reuses declaration-flow storage and reachability information, with
separate queries for imported qualifiers.
Deprecation checks use the original imported value before assignment
recovery, so a conflicting local annotation does not suppress the
import's deprecation warning.
Closes https://github.com/astral-sh/ty/issues/1836.
## Test plan
- Added mdtests for import reassignment, optional-import fallbacks,
existing annotations, wildcard imports, and cyclic loop/match bindings.
- Added imported-`Final` coverage for re-exports, conditional and
unreachable imports, nested and forwarding scopes, class and protocol
members, annotated stub re-exports, and replacement by later imports or
annotations. Core tests check that imported qualifiers remain separate
from genuine declarations and participate in branch merging.
- Added a conflicting-annotation regression that checks both the
assignment error and import deprecation warning while preserving the
recovered binding type.
---------
Co-authored-by: Carl Meyer <carl@astral.sh>
## Summary
Bound methods with incompatible captured receivers currently compare
their function signatures first, which can expand recursive `Self`
bounds unnecessarily. We now check the captured receivers first and
reject the relation immediately when that comparison produces an
unconditional failure.
Function evidence still precedes receiver evidence in the resulting
constraints. Diagnostic collection retains the original evaluation order
so signature mismatches keep their existing error context.
## Summary
This PR properly models the fact that implicit `__set__` calls should
also go through the descriptor protocol themselves, which handles edge
cases like `__set__` methods that are `@staticmethod`s. We also add
bidirectional inference support for (more) descriptor attribute
assignments, which is where the ecosystem improvement comes from:
```py
class DataDescriptor:
def __set__(self, instance: object, value: list[int | None]) -> None:
pass
class Meta(type):
x: DataDescriptor = DataDescriptor()
class C(metaclass=Meta): ...
C.x = [1] # now accepted, previously an error (Expected `list[int | None]`, found `list[int]`)
```
closes https://github.com/astral-sh/ty/issues/4485.
## Ecosystem
25 false positives removed!
## Test Plan
New Markdown tests
When inferring a `ParamSpec`, we currently propagate a declared callable
type as type context if provided. This causes us to discard the inferred
signature of the `ParamSpec` in nested generic calls, leading to false
positives and less precise diagnostics. For example, the following
snippet currently errors:
```py
from typing import Callable
def wrap[**Q](callback: Callable[Q, None]) -> Callable[Q, None]:
return callback
def accept[**P](callback: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...
def no_args() -> None: ...
# error[invalid-argument-type]: Expected `(**P@accept) -> None`, found `def no_args() -> None`
accept(wrap(no_args))
```
Type checking could spend substantial time expanding recursive protocol
members even when a finite member already made an eager comparison
impossible. This is particularly costly when checking explicit receiver
annotations on invariant protocols.
Extend the finite-member shortcut to eager comparisons between
specializations of the same protocol. Incompatible finite requirements
reject the structural relation immediately; matching finite requirements
still fall back to the full interface, since recursive members may
impose additional requirements. Preserve the nominal shortcut for union
simplification and the existing lazy structural comparisons.
Preserve nested protocol mismatch explanations when overload checking
has already compared the same types. During diagnostic generation,
recompute cached unsatisfiable comparisons while reusing satisfiable
constraints and keeping the existing recursion guards.
On the `Chain.flatten` reproducer, the median time across five warmed
debug runs with a single worker and concise output falls from 1.674 s to
0.039 s (about 43× faster). Full and concise diagnostics are unchanged
for this reproducer.
Part of https://github.com/astral-sh/ty/issues/4269.
## Test plan
- Cover an invariant recursive `Chain` protocol with an incompatible
`flatten` receiver and a valid receiver that preserves its element type.
- Verify that matching finite members cannot hide incompatible recursive
requirements.
- Preserve structural assignability when recursion occurs in the source
specialization, including lazy bound-method comparisons during union
simplification.
- Preserve nested protocol-member explanations for a recursive callable
protocol assigned to a union, including the incompatible `payload` type.
- Keep repeated successful alias comparisons fast when diagnosing later
tuple or callable parameter mismatches, including explicit receivers
that leave type-variable constraints.
- Check cache reuse and shared recursion guards when a completed
comparison is repeated.
## Summary
Fix false-positive `invalid-assignment` diagnostics when unpacking list
literals, and consolidate the sequence matching, expansion, and
capture-list inference used for tuples and lists:
```python
first: int
first, *rest = [1, "wrong"]
```
Previously, unpacking the inferred `list[int | str]` lost the positions
of the individual elements and checked `int | str` against the
annotation on `first`. Preserving the literal's positions gives
`Literal[1]` for `first` and `list[str]` for `rest`.
The implementation shares the underlying operations across their
consumers:
- `Tuple::unpack` matches fixed and variable source sequences to fixed
and starred targets. Assignment unpacking, tuple resizing, and
sequence-pattern analysis use this matching logic.
- `TupleBuilder<T, V>` generalizes tuple construction and provides
shared concatenation through `concat_with`. Tuple inference can retain
symbolic `TypeVarTuple` segments, while assignment unpacking can retain
source expressions.
- A shared literal-expansion traversal serves assignment inference,
tuple-expression inference, and source-expression lookup for
diagnostics. It preserves nested literal positions and known prefixes
and suffixes around expansions without assigning persistent fixed-length
types to mutable lists.
- Starred assignments and sequence-pattern captures use the same helper
to infer their new lists, sharing literal and tuple-size promotion rules
with ordinary mutable-collection inference.
List literals now receive the same length-mismatch diagnostics and
unknown-type recovery as tuples. Starred captures from tuples also
follow mutable-list promotion rules, including `list[Unknown]` for empty
captures. The existing large-tuple precision limit counts elements
contributed by literal expansions, and its widening is preserved through
nested unpacking.
## Out of scope: contextual inference for unpacking
Unpacking does not currently use annotations on assignment targets as
type context when inferring the right-hand side. This is a pre-existing
limitation for both tuple and list right-hand sides. For example, these
valid assignments still produce false positives:
```python
from typing import Literal
value: list[Literal[1]]
value, other = ([1], 0) # Inferred list[int] is rejected.
value, other = [[1], 0] # Inferred list[int] is rejected.
```
In both cases, the nested list is inferred without the target's
annotation. Fixing this missing contextual inference is out of scope for
this PR.
## Summary
Emit `missing-slot` when an instance assignment targets a declared
attribute but the instance has neither a matching slot nor an instance
dictionary. Previously, this used `unresolved-attribute`.
This lets users affected by generated stubs such as protobuf's disable
this check without disabling other `unresolved-attribute` diagnostics.
Fixesastral-sh/ty#4375.
## Summary
Add a new `SemanticMode::definitely_has_builtin_binding()` that allows
us to cheaply and easily query whether a builtin name such as `list` or
`int` has been shadowed by a variable in an enclosing scope when viewed
from a given node in the AST. Once this method is in place, it becomes
much more trivial to add autofixes to various diagnostics, which this PR
therefore does.
The new method does not attempt to fully model Python's name-lookup
semantics. It doesn't need to -- it's okay to be conservative when
offering autofixes. The method therefore errs on the side of caution and
only returns `true` if it can be certain that the name passed in was
definitely not shadowed in an enclosing scope.
The new method is similar to the `SemanticModel::has_builtin_binding()`
method that Ruff has had for a long time.
The new `SemanticModel` method is pulled out of
https://github.com/astral-sh/ruff/pull/27634, where I'm using it for
several more diagnostic autofixes that make it much easier to understand
how ty is trying to tell you to rewrite your code (in my opinion).
## Test Plan
mdtests and snapshots
This PR establishes a new invariant that the set of typevars that are
inferable when calling a generic function is _exactly and only_ the
typevars in the function's `GenericContext`.
Surprisingly, this used to not be the case! The main wrinkle is invoking
the constructor of a generic class. In this case, the class typevars are
also inferable. For the most part, we encode that by adding the class
typevars to the generic context of the constructors. But when those
class typevars have an upper bound that contain _other_ typevars, we
were previously including those other typevars in the inferable set as
well. They shouldn't be; this was a hack to cause us to include those
upper bounds correctly when inferring the specialization. This hack
comes from before we had the new solver available. The new solver is
perfectly capable of expressing cross-typevar relationships, and so as
long as we include the upper bounds as additional constraints, we're
good to go.
This pattern also applies to the `Self` typevar that appears in instance
methods, since those implicitly have an upper bound of the class itself.
If the class is generic, we would therefore include the class typevars
in the inferable set — which is actually _incorrect_, since by this
point we already have a specialization for the class, and its typevars
are no longer inferable.
Closes https://github.com/astral-sh/ty/issues/4303
---------
Co-authored-by: Carl Meyer <carl@astral.sh>
Generic classes inheriting recursive protocols can repeatedly expand the
same protocol interface when contextual constructor inference or
diagnostic collection binds explicitly constrained method receivers.
Programs with several inherited recursive members then become
pathologically slow.
Check finite requirements first for nominally inherited protocols, and
stop expanding recursive requirements once their constraints establish
the inherited relationship. Preserve full structural checking when it
remains necessary for erased type parameters, overridden requirements,
concrete-source inference, or diagnostic explanations. Also restrict
eager receiver-compatibility checks to overload selection, where they
actually prune candidates, so single-method binding does not recursively
re-enter the protocol.
Part of astral-sh/ty#4269.
## Ecosystem impact
Werkzeug gains two overload errors and two unused-ignore warnings
because improved contextual inference preserves the actual `sorted`
callback argument instead of widening it to `object`. This exposes its
existing `int | None` sort key; the old lambda-line ignore no longer
covers the call-level error.
## Test plan
- Protocol mdtests cover contextual constructor inference, invalid
constructor arguments, empty-iterable `Never` inference,
concrete/symbolic/unknown constrained receivers, erased type parameters
recovered structurally, and overridden recursive requirements.
- A diagnostic snapshot preserves nested protocol-member explanations
during context collection.
- A constraint-support test verifies exact type-variable identities
without treating declaration-default metadata as semantic support.
- Separate benchmarks cover recursive-protocol constructor inference and
diagnostic collection.
## Summary
When an `invalid-assignment` diagnostic is caused by a previously
declared type, point directly to the annotation that established that
type instead of only annotating the assignment target.
## Example
```py
value: int
value = "three"
```
```text
error[invalid-assignment]: Object of type `Literal["three"]` is not assignable to `int`
--> example.py:2:9
|
1 | value: int
| --- Declared type
2 | value = "three"
| ^^^^^^^ Incompatible value of type `Literal["three"]`
```
Legacy generic aliases and functions failed to discover type variables
that appeared only inside a generic `TypedDict`. Alias specialization
could also incorrectly classify an alias as recursive when a `TypedDict`
member contained an unrelated recursive field. Together, these bugs
prevented valid imported tagged-union aliases from specializing and
produced false-positive diagnostics.
Collect legacy type variables from class-based `TypedDict` definitions,
and restrict recursive-alias detection to the alias structure and its
generic arguments. Update existing overload fixtures to preserve their
diagnostic coverage now that `Self` inside a `TypedDict` is correctly
discovered.
Closesastral-sh/ty#4255.
## Test plan
- Generic `TypedDict` aliases in unions and containers, including
specialized fields, default specialization, type-variable ordering, and
repeated variables.
- Imported tagged-union aliases from stubs, including discriminator
narrowing and concrete field access.
- Recursive `TypedDict` fields that do not make their containing alias
recursive.
- Generic functions whose type variable appears only in a `TypedDict`
parameter.
- Existing overload diagnostic-context scenarios after correcting nested
`Self` discovery.
## Summary
PEP 484's numeric tower means we represent a `float` annotation as the
semantic union `int | float*` and `complex` as `int | float* |
complex*`. We previously rendered those internal unions directly, which
exposed an implementation detail in user-facing output:
```python
def f() -> float:
return 1
reveal_type(f()) # Before: int | float; after: float
```
This change recognizes complete numeric-tower unions during display and
renders them using their canonical annotation spelling, `float` or
`complex`.
The implementation does _not_ preserve explicit unions, e.g., if the
user writes out `int | float`, we still collapse that rather than trying
to preserve it, mostly for simplicity (as per
https://github.com/astral-sh/ty/issues/2184#issuecomment-4345219164).
Closes https://github.com/astral-sh/ty/issues/2184.
## Summary
We had a lot of branches in `signatures.rs` where we were failing to add
error context, which often made our diagnostics less comprehensible than
they could have been. This PR adds context to lots of these branches,
and adds snapshots to cover the new code paths.
There are still lots of `return self.never();` branches, even on this PR
branch, that don't have any error context attached to them. I was too
scared to touch the `ParamSpec`- and `TypeVarTuple`-specific branches in
this PR 🙈 so left them out of scope for now.
## Summary
This is a first step towards #20411. After this, we would work to either
upstream changes or adjust things within Ruff.
Performance improvements have already been upstreamed
(https://github.com/rust-lang/annotate-snippets-rs/pull/437,
https://github.com/rust-lang/annotate-snippets-rs/pull/440)
Re-implemented the following from the fork:
- Hidden snippets
(https://github.com/rust-lang/annotate-snippets-rs/issues/448)
- Renderer-level disabling of hyperlinks
- Jupyter cell indices
(https://github.com/rust-lang/annotate-snippets-rs/issues/449)
- Fixable mark
(https://github.com/rust-lang/annotate-snippets-rs/issues/450)
- `lineno_offset` (maybe not needed if #20648 is taken care of)
- anonymized lines affects origin
(https://github.com/rust-lang/annotate-snippets-rs/issues/451)
- cut indicator (maybe not needed if we can switch to unicode renderer)
Additional hacks to minimize behavior change include
- Adjust upstream's hidden severity behavior to match Ruff's
(https://github.com/rust-lang/annotate-snippets-rs/issues/452)
- How newlines are annotated
(https://github.com/rust-lang/annotate-snippets-rs/issues/454)
- To not indent for line numbers when none will be present
(https://github.com/rust-lang/annotate-snippets-rs/issues/453)
- Enabling `simd` by default
All of the above represents work that needs to be resolved to address
#20411.
`lib.name` hack is used to simplify maintenance with the assumption that
we'll continue working towards #20411.
Behavior changes that were included
- Tweak when implicit padding lines are present
- Fix Origin's line/column is now derived from the primary annotation
- Make consistent the rendering of primary/context annotations
- Fix snippets to show up for empty source (but may degrade #24528)
- Fix handling of term width
- Fix rendering of annotations between newline and first character
(granted, maybe the caller is wrong)
- Tweak multiline annotation markers
New or upcoming features annotate-snippets features that we will be able
to leverage by moving this forward
- `AnnotationKind::Visible` to improve the quality of built-in
code-folding if Ruff were to switch to it
- `DecorStyle::Unicode`
- *(upcoming)* No-graphiscs mode for screen readers (may also be useful
for AIs)
Deferred:
- Moving related `Group`s into the same `Report`
- Using `secondary_title` for any `Group` after the first in a `Report`
- Using a `Snippet`, instead of titles, for "virtual code" like
https://github.com/astral-sh/ruff/pull/27033#discussion_r3622727236
- Switching hidden snippets to `Origin`
## Test Plan
Within cpython, I ran
```console
$ hyperfine -i "../../ruff/target-baseline/release/ruff check" "../../ruff/target-update/release/ruff check" -N -m20 --output=null
Benchmark 1: ../../ruff/target-baseline/release/ruff check
Time (mean ± σ): 27.5 ms ± 1.1 ms [User: 33.0 ms, System: 108.4 ms]
Range (min … max): 25.0 ms … 31.7 ms 94 runs
Warning: Ignoring non-zero exit code.
Benchmark 2: ../../ruff/target-update/release/ruff check
Time (mean ± σ): 28.1 ms ± 2.0 ms [User: 33.4 ms, System: 105.7 ms]
Range (min … max): 24.8 ms … 38.9 ms 102 runs
Warning: Ignoring non-zero exit code.
Warning: Statistical outliers were detected. Consider re-running this benchmark on a quiet system without any interferences from other programs. It might help to use t
he '--warmup' or '--prepare' options.
Summary
../../ruff/target-baseline/release/ruff check ran
1.03 ± 0.08 times faster than ../../ruff/target-update/release/ruff check
```
Before:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/2d94dabf-b28d-48c1-b17c-52aac59fd57e"
/>
After:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/b388ada3-e3d7-4ba0-b90b-1330eb81f4be"
/>
## Summary
Follow-up to #27140 that addresses a couple latent risks in the new
`with_message_override` API.
- Always retain the original headline message: move it to an empty
primary annotation if possible (as we did before), or prepend it as the
first info subdiagnostic (instead of dropping it, as we did before) when
the primary annotation already has a message. This avoids silently
losing existing headline messages. In the current cases where do lose
the prior headline message, it wasn't critical info -- but I also think
it's useful to preserve it. In potential future cases it might be more
important to preserve it.
- Clear a stale custom concise messages when replacing the headline.
This currently isn't relevant because no call error diagnostic uses a
custom concise message, but in general if the headline is being
replaced, that most likely indicates the existing custom concise message
is also no longer correct. Instead we'll just construct a default
concise message from the new headline and primary annotation. If we have
a future case where that's not adequate, the `with_message_override` API
can also accept a new concise diagnostic.
## Test plan
- Updated descriptor `__set__`, property-setter, and custom
`__setattr__` mdtest snapshots to cover invalid arguments, nested
incompatibilities, and multiple argument errors, confirming the
preserved call headline is the first info message.
- Existing missing-argument and overload scenarios continue to retain
their original headline on the primary annotation, and concise
diagnostic expectations remain unchanged.
## Summary
PEP 572 specifies that an assignment-expression target inside a
comprehension binds in the scope containing the outermost comprehension.
Before this change, we left the target inside the comprehension scope,
so it was unresolved when referenced afterward. For example, these two
cases raised false positives on `main`:
```py
def first_comment(lines: list[str]):
if any((comment := line).startswith("#") for line in lines):
reveal_type(comment) # str
def partial_sums(values: list[int]):
total = 0
sums = [total := total + value for value in values]
reveal_type(total) # int
```
This PR makes the walrus target visible in the containing scope while
keeping its value expression in the comprehension scope, where it can
reference iteration variables.
Specifically, the semantic index now records the real assignment in the
comprehension and adds a synthetic binding in the containing scope. If
the comprehension always assigns the target, that binding replaces an
earlier value; if it may not, the earlier value remains possible. Paths
skipped by a filter and assignments passed through nested comprehensions
are kept in order, and type inference reads the bindings left at the end
of the comprehension to determine the exported type.
## What's included vs. excluded
I went through several iterations of this change over the past few
months, and each time they ballooned in scope. Here, I'm trying to
intentionally limit the scope, so this section articulates cases that
came up in Codex review but were explicitly rejected as out-of-scope.
We do not model the zero-iteration path or whether a generator
expression has been consumed:
```py
def empty_comprehension():
items: list[int] = []
[(last := item) for item in items]
print(last) # Runtime NameError; this PR treats `last` as bound.
def deferred_generator(items: list[int]):
pending = ((last := item) for item in items)
print(last) # Runtime NameError until `pending` is consumed; modeled eagerly here.
```
We also conservatively promote exported values because later iterations
can change them. We do not try to retain single-iteration literal
precision:
```py
[(last := 1) for _ in [0]]
reveal_type(last) # int, not Literal[1]
```
We do not compute a fixed point for a walrus whose value changes type
across repeated iterations. We currently infer the exported type from
the first modeled iteration:
```py
value = 0
[value := "" if isinstance(value, int) else 0 for _ in [0, 1]]
reveal_type(value) # str; the runtime value after the second iteration is int
value.upper() # Currently accepted; a fixed-point model would infer str | int
```
(This requires treating the comprehension body as a loop and iterating
its use-def state to a fixed point.)
We also defer all the IDE-specific navigation, references, rename, and
unused-binding behavior to a separate PR (#26476).
Closes https://github.com/astral-sh/ty/issues/162.
There are many places where we check whether a constraint set is always
true or never true as a short circuit, since `false ∧ C == false` and
`true ∨ C == true` for all `C`.
Previously, we did a "deep" satisfiability check, which gives a 100%
accurate answer, but requires walking through the entire BDD, using the
sequent map to calculate derived facts and detect contradictions.
Since these checks are only used for optimizations, we can instead use a
simpler check against the `ALWAYS_TRUE` and `ALWAYS_FALSE` terminals.
These "trivial" checks can return false negatives, but that's okay;
we'll just fall back on calculating the actual AND or OR, which is fine.
To be extra careful, before implementing this I had Codex collect some
data about how often the previous short-circuit check would engage for a
non-terminal-but-always/never-satisfied BDD (data aggregated over
`DateType`, `Expression`, `scipy`, `ibis`, `scipy-stubs`, `pandas`,
`pandas-stubs`, `pydantic`, `sympy`, `mypy`, `jax`, `beartype`, and
`attrs`):
| Short-circuit location | Engaged | Missed by terminal comparison |
Terminal coverage |
|---|---:|---:|---:|
| `ConstraintSet::and` / `or` | 13,057,040 | 42 | 99.9997% |
| Iterator `when_all` / `when_any` | 7,569,371 | 177 | 99.9977% |
| Post-`intersect`: `is_never_satisfied` | 1,022,067 | 367 | 99.9641% |
| Post-`union`: `is_always_satisfied` | 585,184 | 125 | 99.9786% |
The answer: not often at all.
## Summary
Reuse the full call-error diagnostic machinery for implicit descriptor
`__set__` and custom `__setattr__` calls. The call reporter can override
the main lint/message, retain the original call failure on the primary
annotation, map synthesized arguments back to their source ranges, and
add an info diagnostic explaining why the method was called.
This PR also correctly re-classifies failed `__setattr__` assignments as
`invalid-assignment` instead of `unresolved-attribute`.
This PR currently only applies this system to `__set__` and
`__setattr__` calls, but it can be extended to any diagnostic resulting
from a failed implicit dunder call.
Closesastral-sh/ty#4034
## Test plan
Added and updated mdtests covering invalid descriptor values, malformed
`__set__` signatures, concise expected/found output, nested tuple
incompatibilities, overloaded `__setattr__`, invalid attribute names and
values reported together, and instance/metaclass `__setattr__`
assignments.
## Summary
Prior to this change, we could incorrectly reject a call to a stored
bound method obtained from a class-based protocol. Member lookup has
already specialized the method for its receiver, but calling through a
callable union reconstructed the original signature and prepended the
receiver as a synthetic argument. Generic call inference then
structurally checked the inferred `self` annotation again:
```python
from collections.abc import Iterator
from typing import Any
class PeekIterator(Iterator[Any]):
def __init__(self, iterator: Iterator[Any]) -> None:
self._next = iterator.__next__
def __next__(self) -> Any:
# Before: Expected `Self@__next__`, found `Iterator[Any]`
return self._next()
def use_fallback(self) -> None:
self._next = lambda: None
```
The receiver is already bound, so `Iterator.__next__` genuinely takes no
call-site arguments and should not be checked against `Self` again. We
now consume an implicit positional receiver before call inference, apply
the `typing.Self` substitution to the remaining signature, and refresh
its return type. This removes the false positive and avoids re-entering
recursive protocol interfaces during binding, which could otherwise
cause overloaded recursive members to grow the deferred constraint graph
combinatorially.
This also corrects constructor diagnostics for class-based protocols.
Previously we counted the implicit receiver in both the expected and
supplied arity:
```python
from collections.abc import Hashable
def construct(value: Hashable) -> None:
# Before: expected 1, got 4
# After: expected 0, got 3
type(value)(1970, 1, 1)
```
Because binding removes the leading parameter, we preserve its
source-parameter offset so invalid-argument and missing-argument
diagnostics still point at the correct declaration. Explicit, variadic,
keyword-only, and other nonstandard receivers retain the existing
call-inference path; the protocol relation itself is unchanged.
The independent recursive traversal in `redundant-cast` checks is
handled separately in #26708.
Related: <https://github.com/astral-sh/ty/issues/3954>
## Summary
Attach existing assignability error context when an explicit type
argument fails a TypeVar upper bound.
Closes https://github.com/astral-sh/ty/issues/3940.
For the motivating case in that issue, this now clarifies why the
concrete type is not assignable to the protocol.
## Validation
Added mdtest with inline diagnostic snapshot.
## Summary
Report the actual and required read types for incompatible protocol
attributes, distinguishing missing writable capabilities from members
that reject the required write type.
For the motivating case, the diagnostic now explains:
```text
info: type `C` is not assignable to protocol `WithValue`
info: └── protocol member `value` is incompatible
info: └── the member does not accept writes of type `str | None`
```
Related to astral-sh/ty#3940.
## Testing
Added mdtests with inline diagnostic snapshots.
## Summary
Positional class patterns use `__match_args__` to map each subpattern to
an attribute. We previously only diagnosed positional subpatterns for
`collections.abc.Callable`; ordinary classes could supply too many
positional subpatterns, omit `__match_args__`, or expose a definitely
non-tuple value without an `invalid-match-pattern` diagnostic.
This PR derives positional limits from the semantic `__match_args__`
member type. Exact fixed-length tuples provide their length, absent
source-class members accept zero positional subpatterns, and Python's
match-self builtins accept one. Definitely non-tuple member types
produce a dedicated diagnostic instead of being interpreted as an arity.
Fixed tuple information is preserved through variables, typed function
calls, explicit annotations, PEP 695 aliases, inheritance, descriptors,
dataclasses, and named tuples.
```python
class Point:
__match_args__ = ("x", "y")
class Missing: ...
class Invalid:
__match_args__ = ["x"]
def describe(point: Point, missing: Missing, invalid: Invalid) -> None:
match point:
case Point(_, _, _): # error: expected 2, got 3
pass
match missing:
case Missing(_): # error: expected 0, got 1
pass
match invalid:
case Invalid(_): # error: __match_args__ must be an exact tuple
pass
```
Closes https://github.com/astral-sh/ty/issues/3738.
---------
Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
## Summary
`invalid-assignment` adds an implicit-shadowing hint when an assignment
replaces a class or function binding. Prior to this change, the shared
diagnostic construction also attached this hint to attribute assignments
whose declared type happened to be a function, even though assigning an
attribute does not shadow a name binding:
```python
from configparser import ConfigParser
config = ConfigParser()
config.optionxform = str
```
This moves the shadowing-specific context to the general assignment path
and only adds it for direct name targets. Invalid attribute assignments
continue to report the assignability error, but no longer include
misleading guidance about implicit shadowing. The existing diagnostics
for direct class and function shadowing remain unchanged.
The regression snapshot covers the reported `ConfigParser.optionxform`
case.
Closes https://github.com/astral-sh/ty/issues/1990.
## Summary
The `invalid-legacy-type-variable` rule already validates the assignment
shape and declared name, but it did not report when a name had already
been defined in the same scope:
```python
from typing import TypeVar
T = TypeVar("T")
T = TypeVar("T") # error: invalid-legacy-type-variable
```
The diagnostic points back to the preceding definition and considers
earlier bindings and declarations that are reachable from the beginning
of the owning scope.
The implementation reuses the existing per-place use-def snapshot and
reachability predicates, so it only inspects definitions of the target
name rather than scanning every definition in the scope.
Closes https://github.com/astral-sh/ty/issues/3732.
## Summary
Closesastral-sh/ty#3250
`await x` where `x.__await__` is non-callable (e.g. `__await__ = 1`)
pointed the "attribute defined here" annotation at the definition of the
attribute's *type* (`class int:` in typeshed). This PR makes it point at
the user's own binding instead.
---------
Co-authored-by: David Peter <mail@david-peter.de>