mirror of
https://github.com/astral-sh/ruff.git
synced 2026-11-26 14:29:05 +08:00
micha/flat-python-ast
173
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c92a47546c |
[ty] Preserve fixed parameters when comparing gradual callables (#30509)
The "gradual parameters" `*args: Any, **kwargs: Any` are special-cased
to match any possible set of arguments, even when they follow other
"normal" parameters in a signature. But they do not make the _entire_
signature gradual -- calls still must satisfy the other normal
parameters present.
We currently are "too gradual" in our treatment of these signatures,
allowing a callable with an initial typed parameter plus gradual
parameters to be assigned to a callable type that has the wrong type for
its first parameter:
```python
from typing import Any, Callable
def lowercase(value: str, *args: Any, **kwargs: Any) -> str:
return value.lower()
callback: Callable[[int], str] = lowercase # Previously accepted by ty
callback(1) # AttributeError
```
This PR rewrites callable assignability (with a significant net
reduction in Rust LOC!) and now correctly reports the error on this
assignment. The first positional argument binds to `value`, which
requires a `str`. The gradual `*args` and `**kwargs` only describe the
remaining arguments.
Closes astral-sh/ty#5052.
## Ecosystem report
All 104 public ecosystem changes on `8681ef368f` are expected. Most new
errors identify callbacks or overrides that cannot accept an argument
their types promise. [Full ecosystem
report](https://github.com/astral-sh/ruff/pull/30509#issuecomment-6966654399)
|
||
|
|
cf41c5e876 |
[ty] Respect implicit __hash__ = None when a class defines __eq__ (#30145)
A class that defines `__eq__` and omits `__hash__` gets `__hash__ = None` at class creation. ty previously found `object.__hash__` instead and accepted instances of the class and its subclasses where `Hashable` was required. Account for the implicit `None` during class-member lookup. Subclasses inherit it and can restore hashing by defining `__hash__`. Explicit and generated hashes take precedence, including hashes supplied by frozen dataclasses and Pydantic models. An equality protocol's own implicit `None` also stays separate from the hash requirements it imposes on structural implementations. Fixes https://github.com/astral-sh/ty/issues/4941. ## Test plan Compared ty with CPython on the issue reproducer. Python raised `TypeError` for the equality-only class and its subclass, and accepted the subclass that restored hashing. ty now rejects the same two instances for a `Hashable` parameter. Checked Pydantic 2.13.4 at runtime with frozen models that define equality and with a base that provides a custom hash. Pydantic generated hashes for the frozen models, preserved the inherited custom hash when equality was inherited, and left `__hash__ = None` on the subclass that redefined equality over the custom hash. ## Ecosystem report The public run for [`ac783ae`](https://github.com/astral-sh/ruff/commit/ac783ae505378aa9b46acd4e082f0edf6f5e678c) found 23 stable diagnostic changes across five projects. We accept three JAX false positives for this fix. ty loses the relationship between a mask and the callable selected for its type. The other 20 changes follow from recognizing equality-only classes as unhashable, including corrected indexing overloads in static-frame and a missing hash declaration in pandas-stubs. [Full ecosystem report](https://github.com/astral-sh/ruff/pull/30145#issuecomment-6700457278) |
||
|
|
124210f4fd |
[ty] Preserve inherited value types on repeated bare ClassVar annotations (#30396)
A subclass can give a class variable from the base class a new default,
and it can annotate that assignment with bare `ClassVar`. Previously, we
rejected `Record` below because it inferred a one-element tuple for
`group_by`, which we considered an `invalid-mutable-override` (narrowing
the type of a mutable attribute), and then we also rejected the
subsequent assignment to `Record.group_by` as incompatible with the
inferred one-element tuple type.
```python
from typing import ClassVar
class Message:
group_by: ClassVar[tuple[str, ...]] = ()
class Record(Message):
# Previously we inferred `ClassVar[tuple[str]]` as the type of this attribute,
# which is both an `invalid-mutable-override`, and disallows the assignment below.
# Now we "fill in" the bare `ClassVar` with the inherited type instead of the inferred
# type, leaving the declared type of the attribute as `ClassVar[tuple[str, ...]]`.
group_by: ClassVar = ("record",)
Record.group_by = ("record", "source") # previously an error, now OK
```
Ty now checks the default against `Message.group_by`. Inside the
`Record` class body, ty knows that `group_by` is `("record",)`. Later
assignments through `Record` can use any tuple of strings.
A subclass can still redeclare the type explicitly with `ClassVar[...]`.
Follow-up to #30293.
## Ecosystem report
At
[`20ae89c`](https://github.com/astral-sh/ruff/commit/20ae89ca2d779e5cdbdb13d48cc0e26998731662),
ty removes 39 false-positive override errors across five projects. All
39 came from subclasses repeating a bare `ClassVar` with a valid
default. The public run found no new stable diagnostics or project
failures. [Full report and
examples](https://github.com/astral-sh/ruff/pull/30396#issuecomment-6841752291)
|
||
|
|
e1ce434fcd |
[ty] Infer nested classes as read-only attributes (#29346)
ty now accepts `Child.Meta` as an override when it inherits from
`Base.Meta`. Previously, ty rejected the override because the two class
objects are distinct.
```python
class Base:
class Meta: ...
class Child(Base):
class Meta(Base.Meta): ... # OK
class Other(Base):
class Meta: ... # Error: unrelated to Base.Meta
```
`Base.Meta` can still safely reveal the singleton class type of `Meta`,
since the expression `Base` has a singleton class type that doesn't
include subclasses. But a caller reading `obj.Meta` could get
`Child.Meta`, so ty allows for subclasses in the inferred type.
```python
reveal_type(Base.Meta) # <class 'Meta'>
def inspect(obj: Base, cls: type[Base]) -> None:
reveal_type(obj.Meta) # type[Meta]
reveal_type(cls.Meta) # type[Meta]
```
The nested class declaration is read-only. If `obj` is a `Child`,
assigning `Base.Meta` would replace its more specific `Child.Meta`;
making `Base.Meta` read-only allows `Child` to safely narrow its type.
```python
def update(obj: Base) -> None:
obj.Meta = Base.Meta # Error
del obj.Meta # Error
```
A subclass can explicitly declare a writable instance attribute when its
instances need to replace `Meta`.
```python
class Configurable(Base):
def __init__(self) -> None:
self.Meta: type[Base.Meta] = Base.Meta
def configure(obj: Configurable) -> None:
obj.Meta = Child.Meta # OK
```
The same read-only rule applies to nested classes declared on protocols
and metaclasses.
### Django
We have a special-case for Django in main allowing inner `Meta` class
overrides on Django models. This PR doesn't remove that special case.
Two abstract Django models can each declare an unrelated `Meta`. A model
inheriting from both uses the first base’s `Meta` options by default.
Ordinary override checking would report a conflict between those
classes, so ty keeps the Django exception for this case. [Django’s
`Meta` inheritance
rules](https://docs.djangoproject.com/en/5.2/topics/db/models/#meta-inheritance)
Closes https://github.com/astral-sh/ty/issues/4711.
## Test plan
Compared Rust type layouts on aarch64 with debug assertions enabled and
disabled. Widening `TypeQualifiers` to `u16` fit in existing padding in
`TypeAndQualifiers`, `PlaceAndQualifiers`, and `ProtocolMemberData`. All
three kept their original size.
## Ecosystem report
The public comparison found 168 stable diagnostic changes on
`c2d14afc02318e6fdf041a6983447aa7fb6008a6`. All follow from the new
nested-class behavior. [Full ecosystem
report](https://github.com/astral-sh/ruff/pull/29346#issuecomment-6172170919)
- Spark gained two default warnings and Alerta gained eight opt-in
warnings. Both use a nested class accessed through an instance as a
base, so ty can no longer determine the exact method resolution order.
- Three diagnostics disappeared in Spack and Freqtrade.
- 155 existing override errors now display the inferred class-object
types.
|
||
|
|
d5d5ca18a6 |
[ty] Infer value types for bare Final and ClassVar (#30293)
A bare `Final` or `ClassVar` leaves the value type to inference.
Previously, ty passed `Unknown` as the expected type of the initializer.
This could change the result of a generic call and let assignments to a
mutable class variable accept values incompatible with its initializer.
Track whether a qualifier has a type argument. For example, `header:
ClassVar = bytes.fromhex("fd")` exposes `bytes` on the class and accepts
subsequent `bytes` assignments through the class. An explicit
`ClassVar[Unknown]` still exposes `Unknown`.
A bare `Final` instance attribute gets its type from the declaring
class's initializer. A subclass cannot initialize that same final
attribute. For a bare final dataclass field with an ordinary default,
the generated constructor accepts the inferred field type.
A generic call can infer its type arguments from its inputs when it
appears in `yield` or `yield from` in a generator without a return
annotation. The same applies when the call is passed to a callable with
an unknown signature. An explicit parameter or yielded element type of
`Any` still supplies type context.
Split from #30244, which changes generic type-argument inference. The
ordinary dataclass default case overlaps #29576, which also handles
field specifiers and missing defaults. #30255 covers public reads of
module-level finals with an explicit type argument.
Fixes astral-sh/ty#4989.
## Ecosystem report
At
[`28a3e59`](https://github.com/astral-sh/ruff/commit/28a3e5901958260777e605b2ce27477f995dbbab),
ty detects 43 incompatible class-variable overrides across six projects,
removes two false return warnings in pytest, and updates the messages
for three existing errors. All 48 stable changes are expected. [Full
report and
examples](https://github.com/astral-sh/ruff/pull/30293#issuecomment-6782994357)
|
||
|
|
0507c5f66c |
[ty] Rename call-non-callable to not-callable (#30284)
|
||
|
|
284959fb6a |
[ty] Preserve descriptor write contracts in overrides and protocols (#30252)
A descriptor that defines only `__set__` still controls writes to its attribute. For example, ty could accept a subclass property whose setter took only `str` when the inherited descriptor accepted `int`. Check that an override accepts the inherited setter's values. When a method decorator returns a setter-only descriptor on a protocol, reading the member gives the descriptor itself and assigning to it checks the setter's value type. An ordinary annotated attribute remains writable when its type merely permits a descriptor. |
||
|
|
22e77392fb |
[ty] Split invalid-return-type into 3 focussed rules; rename empty-body and unsound-return (#29947)
Co-authored-by: Micha Reiser <micha@reiser.io> |
||
|
|
b9959a107f |
[ty] Preserve the element type when passing tuple as a callback (#30152)
When `rows` is annotated as `Sequence[Sequence[int]]`, ty 0.0.99 infers `tuple[Sequence[int], ...]` after `rows = tuple(map(tuple, rows))`. This causes a false positive when returning `rows` as `tuple[tuple[int, ...], ...]`. Each row was converted to a tuple, and ty can now infer that exact nested type. ty previously synthesized `tuple.__new__` for every tuple specialization. This let it reject calls like `tuple[int, str]()` and enforce the same length constraints on tuple subclasses. This PR narrows that special case to tuples with a fixed length or a positive minimum length. [Original constructor checks](https://github.com/astral-sh/ruff/pull/18987) · [Subclass support](https://github.com/astral-sh/ruff/pull/19469) For bare `tuple` and `tuple[T, ...]`, typeshed already describes the constructor with an `Iterable[T]` parameter and a `Self` return. ty now uses that signature and preserves the inferred element type when building the tuple instance. When `map` passes a `Sequence[int]` row to `tuple`, ty therefore infers `tuple[int, ...]` for the converted row. Fixes https://github.com/astral-sh/ty/issues/4969. ## Test plan Compared the reassignment in the issue across ty versions. Version 0.0.98 accepted the return with `tuple[Unknown, ...]`, and 0.0.99 rejected it with `tuple[Sequence[int], ...]`. With this change, ty reveals `tuple[tuple[int, ...], ...]` and accepts the return. ## Ecosystem report At `5b2ff77e9e`, 25 diagnostics changed across 10 projects. The more precise tuple types clear 12 warnings on valid subclass allocations and one in JAX, expose three invalid operations in colour and ibis, and improve eight existing messages. In HydPy, the change also removes an `Unknown` return warning from a `RiverBasinNumbers` constructor that can produce a tuple of the wrong length. Our new inference here is accurate, we just don't enforce that `__new__` returns something consistent with base classes. `RiverBasinNumbers` should be inheriting `tuple[RiverBasinNumber, ...]` instead of `tuple[RiverBasinNumber]`. [Full ecosystem report](https://github.com/astral-sh/ruff/pull/30152#issuecomment-6712750038) |
||
|
|
4c51cc646d |
[ty] Give abstract class instantiation its own diagnostic rule (#29948)
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com> |
||
|
|
10775b0d4c |
[ty] Rename incompatible override rules (#30142)
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. Fixes astral-sh/ty#2001. --------- Co-authored-by: Alex Waygood <alex.waygood@gmail.com> |
||
|
|
ce0077c3e5 |
[ty] Distinguish attributes missing from some union members (#29944)
## 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.
Fixes astral-sh/ty#2839 and fixes astral-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>
|
||
|
|
b4f3581b1e |
[ty] Avoid expanding runtime type aliases during protocol checks (#29840)
## Summary ty can panic on the call to `extend` below. The fuzzer started hitting this in #29747, but this example also panics on its parent. ```python from typing import Annotated type Alias = Annotated[int, list(iter(aliases))] aliases = [Alias] aliases.extend([Alias]) ``` When ty checks whether the return type of `Iterator.__next__` refers back to the protocol, it encounters the runtime `Alias` object. Expanding its value checks the iterator in the `Annotated` metadata and re-enters the same protocol check. We now visit an alias object separately from the type it denotes. The protocol check can leave `Alias.__value__` unevaluated here and still expand aliases used in annotations. Visitors that look for type variables can read the `T` in a specialized alias object like `Box[T]` without evaluating its value. I reran all 20,001 seeds (`0` through `20000`) against the nightly baseline, `2469f71c13`. The fuzzer found no new panics or timeouts. Seed `9098` produced the same seven diagnostics as the baseline. [Original nightly run](https://github.com/astral-sh/ty/actions/runs/40978355766) Closes https://github.com/astral-sh/ty/issues/4872. |
||
|
|
017c77fcf1 |
[ty] Use # ok comments in mdtests (#29856)
Use `# ok` as the marker for mdtest statements whose expectation is that no diagnostic is emitted. Update the guidance in `AGENTS.md` and replace existing `# no diagnostic` comments in Ruff and ty mdtests. |
||
|
|
b4d38343dd |
[ty] Prioritize finite members in protocol implementation checks (#29542)
This patch has us compare members during protocol-to-protocol comparisons using the same "structural priority" that we use during nominal-to-protocol comparisons. This ensures that we check simple non-recursive members first, often allowing us to determine a (failed) comparison result before having to perform any expensive recursive member checks. |
||
|
|
b0f95269f9 |
[ty] Preserve checks for recursive descriptor setter types (#29148)
## Summary
This PR fixes a stack overflow when checking a protocol's writable
member whose descriptor setter accepts a recursive type. For example,
checking the assignment below previously aborted the process instead of
reporting an invalid assignment:
```python
from __future__ import annotations
from typing import Protocol
class Recursive[T](Protocol):
next: Recursive[list[T]]
class Descriptor:
def __init__(self, getter: object) -> None: ...
def __get__(self, instance: object, owner: type | None = None) -> int:
return 1
def __set__[U](self, instance: object, value: Recursive[int]) -> None: ...
class HasValue(Protocol):
@Descriptor
def value(self) -> int: ...
def update(obj: HasValue) -> None:
obj.value = 1 # Invalid: the setter requires Recursive[int].
```
The setter's unused `U` triggers a search to determine whether the
accepted value type depends on that type parameter. The existing search
follows `next` through `Recursive[int]`, `Recursive[list[int]]`,
`Recursive[list[list[int]]]`, and so on. Its recursion guard remembers
exact types, so these changing specializations never repeat and the
search overflows the stack. Removing `U` avoids the search and the
crash.
We replace that general type search with a dependency check that
recognizes repeated definitions and inspects the arguments of recursive
references without repeatedly expanding their bodies. Here, it
establishes that the setter accepts `Recursive[int]` independently of
`U`, so we can report the invalid assignment normally. The same fix
covers recursive `TypedDict`s and type aliases, while retaining checks
for assignments and protocol compatibility.
Co-authored-by: Ibraheem Ahmed <ibraheem@ibraheem.ca>
|
||
|
|
477638fb1b |
[ty] Compare protocol receiver restrictions before binding (#29443)
Improve compatibility checks for protocol methods with explicit receiver restrictions. When both receivers specialize the same protocol, we can use the variance of the protocol's typevars to prove that the target restriction implies the implementation's restriction. This lets us avoid recursive receiver checks that introduce fresh type variables. We preserve the existing structural fallback when the variance-based proof cannot establish compatibility. Pulled this out of #29027; it claws back one of the larger perf regressions from that PR, but is a standalone fix that can be reviewed/merged in isolation. |
||
|
|
2c6359372b |
[ty] Infer return intersections from correlated call specializations (#28303)
## Summary This PR builds on the intersection constraint collection in #28677. It improves the precision of our inferred return types in cases when an argument-side intersection (or overloaded callable) results in multiple independent valid solutions. When an argument to a generic function is an intersection (or an overloaded callable), this often results in multiple valid solutions for the call. For example, if you pass `Sequence[A] & Sequence[B]` to `def first[T](value: Sequence[T]) -> T`, the constraint solver will correctly report that both `T = A` and `T = B` are equally valid independent solutions. Currently we union these valid solutions together, resulting in the overly-conservative inference `T = A | B`, even though the returned object in this case must be both `A` and `B`. This means that narrowing the argument (e.g. from just `Sequence[A]` to `Sequence[A] & Sequence[B]`) can actually widen the return type (from just `A` to `A | B`), leading to false positives. Other type checkers just arbitrarily pick either `A` or `B` as the return type in this scenario, which leads to fewer false positives than our current `A | B`, but is unsatisfyingly arbitrary, and can still lead to some false positives, because it can effectively ignore narrowing. We can do better (at least in some cases). It's tempting to say that we should just intersect the valid solutions instead, giving `T = A & B` as our single solution. For the simple `-> T` case above, that gives the correct result `A & B`. But if we had instead `def boxed_first[T](value: Sequence[T]) -> Box[T]` with covariant `Box`, the correct return type is `Box[A] & Box[B]`, not `Box[A & B]`. (It is true for some covariant types, but not all, that `Box[A & B]` is equivalent to `Box[A] & Box[B]`.) So we cannot solve `T` directly to `A & B`, but we can say that if `T = A` and `T = B` are both valid solutions, then `Box[A]` and `Box[B]` are both independently valid inferences for the overall return type of the call, thus `Box[A] & Box[B]` is a valid inference for the call: the returned object must be both a `Box[A]` and a `Box[B]`. Fixes astral-sh/ty#4716. Partially addresses [astral-sh/ty#3557](https://github.com/astral-sh/ty/issues/3557); the union migration and the documented precision limitations below remain separate work. ## Caveats Most of the code in this PR is identifying and carving out cases where the above logic is not (yet) safe to apply. ### Solver limitations and deferrals This can be because of limitations in the inference machinery (e.g. return refinement does not yet support `ParamSpec` or `TypeVarTuple`). It can also be just because we've deferred some complex cases to future work (constructors, `functools.partial`). We also fall back to conservative union-merged specialization in case the constraint solver exceeded its budget, in which case it may have an incomplete solution. For intersection refinement to be valid, each solution must validate every argument (result in a valid call if it specializes the function parameter types). This would be a given if the constraint solver were perfect at collecting all relevant constraints, but it isn't yet. In particular, we can infer constraints from incompatible arguments (e.g. `list[int] | None` vs `list[T]` infers `T = int`, `tuple[int, str]` vs `tuple[U, int]` infers `U = int`) and in general we can have "solutions" that correspond to calls which failed. Also some unsupported cases drop constraints, e.g. `list[int] | set[str]` vs `list[T] | set[T]` infers no constraints at all. We therefore, for now, revalidate each specialization against the original arguments (that is, for each candidate solution, specialize the parameter and argument types accordingly, then re-check each argument/parameter pair) before deciding to intersect them. This should be removable in the future when the solver is more complete. Currently we treat overloaded callables in constraint collection as if they were intersections of callables, and collect constraints from all overloads, but this is not quite right, since overloads are ordered; in overlapping cases we should prefer the first match. Incompatible overlapping return types can currently intersect to `Never`, including for `operator.mul` with a `Fraction`. ### Inherent There are also some caveats which are inherent, rather than due to any temporary solver limitation. #### Gradual types If one argument establishes that `int` and `str` are possibilities for `T`, and another argument assigns `Any` to `T`, it is not safe to intersect `int` and `str` specializations of the return type: the assignability of `Any` to `T` could rely on different materializations for different specializations of `T`. In other words, the `Any` might materialize to something which would have ruled out either `int` or `str` as a solution. So this reliance on gradual assignability prevents us from being confident that the returned value satisfies both specialized return types. For now, we catch this gradual case in the "argument revalidation" described above, by using subtyping instead of assignability to revalidate any argument-to-parameter assignment that involves an inferrable typevar, so we will not consider a specialization that requires gradual assignability as a candidate for intersecting. In the future, if the constraint solver preserves the fact that gradual evidence was required for a given solution, we can consume that directly instead of needing revalidation. Currently if no candidate specialization survives argument revalidation, we fall back to the union-merged specialization, but this should also be improved in future work: ideally gradual evidence would result in gradual output (more like an `AnyOf` type), not a strict union. #### Invariant difference There are cases where e.g. both `list[A]` and `list[B]` could be valid but mutually exclusive inferences for a generic call, for example if the function returns an empty list: ```py def fresh[T](type_source: Sequence[T]) -> list[T]: return [] ``` If we call this function with an argument of type `Sequence[A] & Sequence[B]`, then `T = A` and `T = B` are both valid solutions, but they are mutually exclusive inferences. The runtime object `[]` (with different static type tags) can inhabit either `list[A]` or `list[B]`, and the return type of a call to `fresh()` could be validly considered either a `list[A]` or a `list[B]`, but it cannot be considered both at once (that intersection would simplify to `Never`, but the call can return.) Similar cases can occur with structural types: `TypedDict`, `Protocol`, and callable types. Currently, we handle this by avoiding intersecting return types whenever valid alternatives differ in an invariant component of the return type. In these cases we try falling back to the union-merged specialization (`T = A | B`), but if that specialization would fail the call, we instead union the specialized return types from the valid alternatives (infer e.g. `list[A] | list[B]`.) ## Ecosystem report The [full ecosystem report](https://github.com/astral-sh/ruff/pull/28303#issuecomment-5701401704) for head `48f5f1dbf604` confirms expected precision improvements in Prefect, Spark, Rich, pip, and scipy-stubs. Sixteen diagnostics are removed; one Spark return error becomes an `unsound-return-statement` warning because a pre-existing loop-inference limitation still contributes `Unknown`. No ecosystem regressions were identified. |
||
|
|
4fe2a2a908 |
[ty] Preserve Self when checking universal protocols (#29207)
Protocols declaring a writable `__class__: type[object]` currently are incorrectly considered "equivalent to `object`" and accept arbitrary objects. Each subclass's inherited setter accepts only `type[Self]`, so these protocols are not equivalent to `object`. Check the full protocol against an arbitrary receiver type, preserving receiver-specific `Self` requirements in attributes and methods. Protocol attribute annotations also retain their `Self` binding scope through inheritance and unannotated defaults. Read-only `__class__` protocols and writable contracts accepting only `type[Self]` or `Never` retain their existing behavior. ## Ecosystem report At head [`588c1f8392`](https://github.com/astral-sh/ruff/commit/588c1f8392da077263686f10d41f89c1e5901cf2), all 21 stable scipy-stubs changes are expected: corrected overload selection removes 12 type assertion failures and 7 incorrect deprecation warnings, and adds 2 correct deprecation warnings. No ecosystem regressions found. [Full analysis](https://github.com/astral-sh/ruff/pull/29207#issuecomment-6048924278). ## Ecosystem report At head [`3a0dfbcd01`](https://github.com/astral-sh/ruff/commit/3a0dfbcd01b2eddeb47d42904585dc41dde3457a), all 38 ecosystem changes are expected. Corrected sentinel-overload selection in scipy-stubs fixes result types and deprecation reporting. Binding `Self` in protocol attributes makes Werkzeug's header classes satisfy their protocol; the recovered types expose two optional warnings, including an existing descriptor annotation that omits `None`. No ty regressions were found. [Full analysis](https://github.com/astral-sh/ruff/pull/29207#issuecomment-6048924278). |
||
|
|
ef6d36ac43 |
[ty] Reject runtime_checkable on non-protocol classes (#29460)
## Summary We now report `invalid-argument-type` when `typing.runtime_checkable` or `typing_extensions.runtime_checkable` is applied to a non-protocol class, including a concrete subclass of a protocol. These applications raise `TypeError` at runtime. The check also covers direct calls. ```python from typing import Protocol, runtime_checkable @runtime_checkable # Error: an ordinary class is not a protocol. class Ordinary: ... @runtime_checkable # OK: P directly inherits from Protocol. class P(Protocol): ... @runtime_checkable # Error: inheriting from P does not make this a protocol. class Concrete(P): ... runtime_checkable(Ordinary) # Error: direct calls have the same restriction. ``` Closes https://github.com/astral-sh/ty/issues/4470. |
||
|
|
217848df61 |
[ty] Preserve bound receivers for strict signature checks (#29396)
Protocol matching could incorrectly establish strict subtyping when an
explicitly annotated receiver was only assignable through gradual types.
Preserve the bound receiver and its annotation alongside cached
assignability constraints, so eligibility uses the active relation after
specialization and freshening.
For example, `Source[Any]` remains assignable to `IntSource`, but it is
not a strict subtype: `get` requires a receiver compatible with
`Source[int]`.
```python
from typing import Any, Protocol
from ty_extensions import static_assert
from ty_extensions._internal import is_assignable_to, is_subtype_of
class Source[T]:
def get(self: "Source[int]") -> int:
return 0
class IntSource(Protocol):
def get(self) -> int: ...
static_assert(is_assignable_to(Source[Any], IntSource))
static_assert(not is_subtype_of(Source[Any], IntSource)) # previously failed
```
This is a prerequisite to avoid regressions in #28303.
## Ecosystem report
50 changes reflect corrected strict-subtype checks for
receiver-restricted NumPy iteration and tuple hashing; Ibis adds 12
duplicate copies of existing errors. The existing deduplication of
diagnostics on calls to unions of constructors is confined to deferred
downstream constructor calls (in Ibis, metaclass `__call__` → generated
`__init__`; custom `__new__` → `__init__` is another route); "normal"
union constructor calls don't deduplicate. This deduplication should
either be applied more generally, or be removed; either one is out of
scope here. [Full ecosystem
report](https://github.com/astral-sh/ruff/pull/29396#issuecomment-6202295665)
(head `0ace479a7f9a`).
|
||
|
|
3b412c3180 |
[ty] Revert protocol interface member walk (#29462)
Reverts #26996. I wrote "merge" when I meant "close", so the PR was merged by mistake. This restores the previous protocol member lookup and removes the tests and benchmarks added by that PR. |
||
|
|
77c28c03be |
[ty] Walk protocol interfaces in member order (#26996)
We reduce repeated `BTreeMap` lookups when comparing similarly sized protocol interfaces by walking source members in name order. The walk remains lazy and restarts when structural-priority ordering returns to an earlier member name, preserving early failure and recursive constraint ordering. When the source has more than twice as many members as the target, we keep direct lookups so small target interfaces do not require scanning a large source. CodSpeed reports a [4.98% efficiency improvement](https://github.com/astral-sh/ruff/pull/26996#issuecomment-5017613608) for `many_protocol_members_mismatch` in simulation, with no reported regressions among the other comparable benchmarks. This is a focused microbenchmark result. The new dense, sparse, early-mismatch, and mixed-priority benchmarks have no comparative baseline yet; local native timings were inconclusive. |
||
|
|
355b42a771 |
[ty] Avoid writable override contracts from object (#29373)
Fix false `invalid-mutable-override` diagnostics when slotted classes assign metadata such as `__module__`. The attributes declared on `object` do not establish an instance-write contract for subclasses, because `object` provides no instance attribute storage. Read-type compatibility and write contracts explicitly declared by user-defined bases remain checked. Fixes astral-sh/ty#4725. ## Test plan Checked CPython 3.13 behavior: assignments to `__module__`, `__doc__`, `__annotations__`, `__dict__`, and `__str__` on `object()` fail. Also verified that `__class__` assignment fails for `object()` but can succeed between compatible slotted user-defined classes. ## Ecosystem report Analyzed head: [`56847d246246b4381d4873a36495e0d91d89f469`](https://github.com/astral-sh/ruff/commit/56847d246246b4381d4873a36495e0d91d89f469). The ecosystem shows 23 expected false-positive removals across eight projects: getter-only metadata properties and metadata assignments in slotted class bodies. All changes are intended, with no ecosystem concerns remaining. [Full report](https://github.com/astral-sh/ruff/pull/29373#issuecomment-6173018962). |
||
|
|
e26e6d2a54 |
[ty] Collect intersection inference through constraint relations (#28677)
Intersection arguments to generic functions can offer several valid specializations, with relationships between their type variables and other arguments. Collect these constraints through the full constraint-set-assignability type relation so inference preserves variance, alternatives, and correlations. For example, another argument can select `T = A` from the alternatives provided by `Sink[A] & Sink[B]`. There are some cases we have to carve out: - Constraint-set assignability can currently lose constraints when gradual types are involved. https://github.com/astral-sh/ruff/pull/28307 will fix this; until then we have to keep gradual types in the old solver to avoid regression. - ParamSpec and TypeVarTuple must be kept in the old solver until the new solver supports them. This includes callables with `ParamSpec` or `TypeVarTuple` that are nested inside an intersection. We don't handle this problem in general, but by far the most common case is an intersection with `~AlwaysTruthy` or `~AlwaysFalsy`. We avoid regression in that scenario by, whenever we have a single-positive-element intersection in covariant position, dropping the negative element(s) and recursing into the positive element in the old solver, instead of passing the intersection to the new solver. This is a sound upcast, and negative intersection elements generally don't contribute any constraints to generics solving. This depends on #29014 for validating declared upper bounds when an inferred specialization contains caller-fixed type variables. This partially addresses astral-sh/ty#3557 and astral-sh/ty#2799. Argument checking and return inference still use the union-merged specialization when there are multiple valid solutions, and we haven't moved unions into the new solver yet. Fixes astral-sh/ty#3719. ## Ecosystem report Analyzed head: `77137c770276c0910f4f8fc14bbaa44f233ee82e`. Four false positives are removed in Tanjun and xarray; Tornado gains a correct diagnostic under strict generic narrowing. The general caller-fixed-variable solver limitation also reproduces on main and is tracked separately in [ty#4696](https://github.com/astral-sh/ty/issues/4696). [Full ecosystem report](https://github.com/astral-sh/ruff/pull/28677#issuecomment-5780439815). |
||
|
|
eb625e43e4 |
[ty] Check overrides of receiver attribute declarations (#28557)
## Summary
We now check receiver attribute declarations against inherited attribute
contracts:
```python
class Base:
value: int
class Child(Base):
def __init__(self) -> None:
self.value: str = "" # invalid-attribute-override
```
This covers attributes declared in methods on either side of an
override, including generic specializations and inherited slots. The
opt-in mutable-override rule also rejects narrowing a receiver
declaration's type. Plain assignments continue to initialize or update
an inherited attribute without introducing a new declaration.
We compare each class's own declarations so that inherited lookup cannot
hide an incompatible receiver annotation. Names absent from the bases
are skipped before inferring method bodies.
Part of https://github.com/astral-sh/ty/issues/2158.
|
||
|
|
002095b37d |
[ty] Check attribute and property override types (#28556)
## Summary We now check that attribute and property overrides preserve the types that can be read and written through the superclass. The checks extend `invalid-attribute-override` and introduce two separately configurable rules, following the distinction proposed in [ty#2158](https://github.com/astral-sh/ty/issues/2158). ### `invalid-attribute-override` We reject ordinary attributes whose readable type is incompatible with the inherited declaration. This rule is enabled by default: ```python class Base: value: int class Child(Base): value: str # Now rejected: invalid-attribute-override. ``` The rule also rejects removing write access, such as replacing a writable attribute with a `Final` attribute, and retains the existing checks for incompatible `ClassVar` qualifiers. ### `invalid-property-type-override` We reject incompatible property result types, setters that accept fewer values than the inherited setter, and getter-only properties that replace writable attributes. This rule is also enabled by default: ```python class Base: @property def value(self) -> int: return 0 class Child(Base): @property def value(self) -> str: # Now rejected: invalid-property-type-override. return "" ``` A read-only property returning `bool` would be a valid override of this `int` property. Reads can become more specific; writes must continue to accept every value permitted by the superclass. ### `invalid-mutable-override` Narrowing a writable attribute's type preserves reads but restricts writes. We report this separately, and leave the rule disabled by default: ```python class Base: value: int class Child(Base): value: bool # invalid-mutable-override, when enabled. def reset(obj: Base) -> None: obj.value = 42 child = Child() reset(child) # Allowed through Base, but child.value is no longer a bool. ``` This distinction lets users opt into mutable invariance without changing the other override checks. ## Case analysis ### Cached properties in Home Assistant The [ecosystem report](https://fed09ff3.ty-ecosystem-ext.pages.dev/diff) adds 6,986 `invalid-property-type-override` diagnostics. Home Assistant accounts for 6,863 of those, including 6,861 cases where a read-only property replaces a writable attribute. A common pattern is [BlueCurrentEntity.available](https://github.com/home-assistant/core/blob/8f4c394961405acec82bc01f24620359736617b3/homeassistant/components/blue_current/entity.py#L43), which replaces the inherited [Entity.available cached property](https://github.com/home-assistant/core/blob/8f4c394961405acec82bc01f24620359736617b3/homeassistant/helpers/entity.py#L870) with a getter-only property: ```python from functools import cached_property class Entity: @cached_property def available(self) -> bool: return True class IntegrationEntity(Entity): @property def available(self) -> bool: # Now rejected: invalid-property-type-override. return True def mark_unavailable(entity: Entity) -> None: entity.available = False mark_unavailable(Entity()) # Succeeds. mark_unavailable(IntegrationEntity()) # Raises AttributeError. ``` Both getters return `bool`, but the override removes a supported write (a `cached_property` stores its value in the instance dictionary and permits assignment to replace it, even before the first read, so it's writable). This PR retains the diagnostic (it's correct, after all): a function accepting `Entity` can assign to `entity.available`. Replacing the cached property with a getter-only property makes that valid operation fail on subclass instances. (pyright 1.1.411 in standard mode rejects this override, but mypy 2.3.1 and pyrefly 1.2.0 with default checks accept it.) Part of https://github.com/astral-sh/ty/issues/2158. |
||
|
|
19cb997763 |
[ty] Avoid expanding recursive protocol materializations (#29026)
Comparing a recursive protocol with its materialization can repeatedly expand its members and specialized receivers. This can make an async context manager with an `AsyncGenerator` return annotation extremely slow to check. Use the known relationship between a protocol and its own materializations to avoid unnecessary assignability checks, and defer generic-argument equivalence checks until materialization needs them. When a conservative proof establishes that materialization is a no-op, remove it before comparing different specializations and use the ordinary protocol comparison for the result. The proof rejects gradual or provisional requirements that it cannot establish as unchanged. Fixes astral-sh/ty#4629. ## Test plan Added mdtests cover recursive protocol materialization with static and gradual members, stable and growing specializations, static type-parameter bounds and constraints, explicit receivers, properties, descriptors, nested invariant protocols, and inference cycles, including paired legacy and PEP 695 cases. A PEP 695 async context manager regression covers yielding a list of protocol instances with a static bound and a recursively specialized receiver. An incremental test checks invalidation when an imported member type changes between `int` and `Any`; member-walker unit coverage checks gradual types in callable signatures and variadic property setters. Benchmarks cover member-count scaling, growing specializations, specialized receivers, and an async context manager with a recursively specialized receiver. ## Ecosystem report At head `25e8a583c6168294df4820970fdd25ece2fa5443`, the [ecosystem run](https://github.com/astral-sh/ruff/actions/runs/37485799653/attempts/1) reports seven diagnostic removals in pyochain: four parametrized functions retain their callable signatures, and three nested iterator assertions retain their expected types. The structured diff is identical to the previously verified report, and no project failures changed. These changes are consistent with the declared overloads; no new ecosystem regression was found. See the [full ecosystem report](https://github.com/astral-sh/ruff/pull/29026#issuecomment-5939774597). |
||
|
|
52612f67ba |
[ty] Inherit annotations for unannotated subclass defaults (#28575)
## Summary
We now retain an inherited annotation when a subclass assigns a new
default without redeclaring the attribute. The annotation provides
context for the initializer and remains the public attribute type, so
reads, writes, and writable protocol matching use the same type.
```python
class Base:
items: list[int] = []
values: tuple[int, ...] = ()
class Child(Base):
items = []
values = ()
def check(child: Child) -> None:
reveal_type(child.items) # list[int], previously list[Unknown]
reveal_type(child.values) # tuple[int, ...], previously tuple[()]
child.items.append("wrong") # Now rejected.
child.values = (1, 2) # Now accepted.
```
Initializers are checked against the inherited annotation, including
specialized generic bases. Inherited `ClassVar` restrictions are
preserved, and explicit subclass annotations continue to supply their
own declared type.
## Case analysis
Here are a few cases that deserve some scrutiny (compared against mypy
2.3.1, pyright 1.1.411, and pyrefly 1.2.0 with Python 3.12, pyright's
standard mode, and pyrefly's default preset).
### Concrete defaults and factories
An optional attribute remains optional when a subclass supplies a
non-optional default. We now reject the read below, as do pyright and
pyrefly. Mypy infers `str` for the subclass attribute and accepts it:
```python
class Base:
value: str | None = None
class Child(Base):
value = "ready"
def read(child: Child) -> str:
return child.value.upper() # ty, pyright, pyrefly: error; mypy: OK.
```
The inherited declaration still permits assigning `None`. So a concrete
default does _not_ establish a non-`None` type, which leads to errors
like [setuptools' concatenation with an inherited optional object-file
extension](https://github.com/pypa/setuptools/blob/4e612f9e44ecfad130d0b2a27a2dce0740599b4b/setuptools/_distutils/compilers/C/cygwin.py#L240).
Class-valued factories have the same tradeoff. [Artigraph's
adapters](https://github.com/artigraph/artigraph/blob/a158a7eae0406c35905d8bb3b2f27a733c2c18bc/src/arti/types/numpy.py#L81)
lose concrete constructor parameters when the public attribute retains
`type[Model]`. Pyright and pyrefly agree with us; mypy retains the
concrete constructor:
```python
from typing import ClassVar
class Model:
pass
class SpecialModel(Model):
def __init__(self, extra: int) -> None:
pass
class Base:
factory: ClassVar[type[Model]]
class Child(Base):
factory = SpecialModel
def create() -> Model:
return Child.factory(extra=1) # ty, pyright, pyrefly: error; mypy: OK.
```
### Writable protocol matching
If a subclass attribute can be read and written as `int | str`, it
implements the equivalent writable protocol member. We now accept the
return below, as does pyrefly. Mypy rejects both the string assignment
and the return because it infers `int` for the subclass attribute:
```python
from typing import Protocol, reveal_type
class Base:
value: int | str = 0
class Child(Base):
value = 1
class Writable(Protocol):
value: int | str
def convert(child: Child) -> Writable:
reveal_type(child.value) # ty, pyright, pyrefly: int | str; mypy: int.
child.value = "allowed" # ty, pyright, pyrefly: OK; mypy: error.
return child # ty, pyrefly: OK; mypy, pyright: error.
```
### Descriptors with a wider setter
HydPy declares a [base descriptor with a `Never` setter
input](https://github.com/hydpy-dev/hydpy/blob/005841db875b9099cb69ec143857b84157d69009/hydpy/auxs/interptools.py#L53),
then installs a [subclass descriptor accepting
integers](https://github.com/hydpy-dev/hydpy/blob/005841db875b9099cb69ec143857b84157d69009/hydpy/auxs/anntools.py#L573).
The concrete setter supports the [subsequent
writes](https://github.com/hydpy-dev/hydpy/blob/005841db875b9099cb69ec143857b84157d69009/hydpy/auxs/anntools.py#L524),
but the inherited annotation does not expose that capability:
```python
from typing import Generic, Never, TypeVar
T = TypeVar("T", contravariant=True)
class Descriptor(Generic[T]):
def __set__(self, instance, value: T):
pass
class Base:
value: Descriptor[Never]
class Child(Base):
value = Descriptor[int]()
def update(self):
self.value = 1 # ty, pyright, pyrefly: error; mypy: OK.
```
Explicitly annotating the subclass assignment as `value:
Descriptor[Never] = Descriptor[int]()` produces the same write error in
ty before this change, and all three other checkers reject it too.
### Assigned functions and descriptor values
Scrapy [assigns a function to an inherited callback
attribute](https://github.com/scrapy/scrapy/blob/f52c4efe1b47874fed1924a7dc4c0e68b289b3c5/tests/test_engine_loop.py#L334).
The runtime call works because accessing the function through an
instance binds `self`. The initializer check instead compares the
unbound, two-parameter function with the inherited one-parameter
callable annotation:
```python
from collections.abc import Callable
class Response:
pass
class Spider:
parse: Callable[[Response], None]
def default_parse(spider: Spider, response: Response) -> None:
pass
class Child(Spider):
parse = default_parse # ty, pyright, pyrefly: error; mypy: OK.
```
Werkzeug encounters a similar distinction when [installing a descriptor
as
`LocalProxy.__doc__`](https://github.com/pallets/werkzeug/blob/f97c305673ba121a1dae6764c37e8be48907a1d1/src/werkzeug/local.py#L534).
Attribute access can return a string, but the assigned descriptor object
is not assignable to the inherited `object.__doc__: str | None`
annotation:
```python
class Descriptor:
def __get__(self, instance, owner) -> str:
return "documentation"
class Child:
__doc__ = Descriptor() # ty, pyright, pyrefly: error; mypy: OK.
```
### Class-creation metadata and inherited qualifiers
The [protobuf-generated stubs checked by
dd-trace-py](https://github.com/DataDog/dd-trace-py/blob/739849b1cf62399373aa742555584c8418ff3454/tests/contrib/grpc_aio/hellostreamingworld_pb2.pyi#L10)
use a list for `__slots__`, while the inherited annotation specifies a
tuple:
```python
class Message:
__slots__: tuple[str, ...]
class Child(Message):
__slots__ = ["field"] # ty, pyright, pyrefly: error; mypy: OK.
```
Python accepts the list. The static error follows the inherited
annotation, which is narrower than the runtime mechanism permits. Since
`__slots__` describes each class's layout, this is a question about how
its annotation should model class-creation metadata. We currently apply
the ordinary inheritance rule, as do pyright and pyrefly.
|
||
|
|
3d834a01bf |
[ty] Treat imports as bindings instead of declarations (#27325)
## 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>
|
||
|
|
f4fd1244d8 |
[ty] Reject abstract class instantiation (#28167)
## Summary
Previously, we allowed constructor calls to classes with unimplemented
abstract methods. We now report `instantiate-abstract-class` in such
cases:
```python
from typing import Protocol
class Base(Protocol):
def method(self) -> int: ...
class Abstract(Base): ...
class Concrete(Base):
def method(self) -> int:
return 42
Abstract() # Before: no error. After: instantiate-abstract-class.
Concrete() # Before and after: no error.
```
The check covers `@abstractmethod`, implicitly abstract protocol
methods, and abstract property accessors. We reuse the analysis for
`@final` classes so the two checks agree on which methods remain
abstract. Methods decorated with `@abstractmethod` are checked even when
the class does not use `ABCMeta`.
This moves
[`protocols_merging`](https://github.com/python/typing/blob/cf943ccbea5596ef969eec6e2260097ff697b7ba/conformance/tests/protocols_merging.py)
from Partial to Pass and reports three missing errors in
[`protocols_explicit`](https://github.com/python/typing/blob/cf943ccbea5596ef969eec6e2260097ff697b7ba/conformance/tests/protocols_explicit.py).
The other 143 conformance files are unchanged.
Closes https://github.com/astral-sh/ty/issues/1877.
Based on @AlexWaygood's work in #23395.
---------
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
|
||
|
|
93fe9c6567 |
[ty] Reject reassignment of enum members (#28462)
## Summary
We now reject assignments to enum members on class objects. Previously,
we accepted the following even though it raises `AttributeError` at
runtime:
```python
from enum import Enum
class Answer(Enum):
NO = 0
YES = 1
# Before: no error.
# After: error[invalid-assignment]: Cannot assign to attribute `NO` on type `<class 'Answer'>`
Answer.NO = 5
```
This covers aliases, augmented assignments, and generic class receivers.
Enum members are marked read-only during member lookup, so the same
restriction applies when checking writable protocols. Non-member
attributes and instance shadowing remain assignable.
Closes https://github.com/astral-sh/ty/issues/4127.
|
||
|
|
e11135d217 |
[ty] Default-specialize class objects in meta-protocol checks (#28265)
Bare generic class objects were checked against `type[P]` using constructor return types that retained the class's type variables, even though ordinary class-member lookup already applies the default specialization. This could reject compatible classes and leak class-scoped type variables into generic protocol inference. In pyochain, those variables also trigger an expensive recursive protocol proof when passing bare `Ok` to `and_then`; this PR improves our overall type-check time for pyochain by ~8x. Apply the default specialization when obtaining the constructed type for meta-protocol checking and inference, including inference from unions of class objects. A shared helper keeps those paths consistent. Explicit specializations, custom `__new__` and metaclass `__call__` return types, and all structural member checks are preserved. Ordinary constructor and callable inference are unchanged. One of many PRs fixing problems uncovered by [astral-sh/ty#4269](https://github.com/astral-sh/ty/issues/4269). ## Test plan Added mdtests cover declared and missing type-parameter defaults, incompatible default specializations, explicit arguments, unions of bare classes, preservation of caller type variables, unbound methods, `functools.partial`, custom `__new__` returns, and metaclass `__call__` returns. Local checks on all 115 tracked Python files in the unchanged pyochain checkout retain the same 514 diagnostics. A callable-inference control still infers `Result[str, str]` when passed bare `Ok`. |
||
|
|
689a33fd36 |
[ty] Add rules to detect always-truthy and always-falsy conditions (#28034)
## Summary Builds on #28032. Add two rules for boolean tests whose truthiness is statically known: - `redundant-condition`, enabled by default at warning severity, catches cases such as an uncalled function or method, an unawaited coroutine, a generator tested for emptiness, or a tuple whose length makes its truthiness constant. - `redundant-condition-strict`, disabled by default, covers boolean/integer conditions, conditions whose outcome is fixed only by short-circuit evaluation, and conditions containing walrus expressions. These can expose real bugs, but are also much more likely to be intentional. The checks reuse ty's truthiness inference and apply to `if`/`elif`, `while`, assertions, match guards, conditional expressions, comprehension filters, and unary `not`. The operands of `and`/`or` are checked when the expression is used as a condition. The main design question is which statically redundant tests are likely to represent mistakes. The implementation deliberately prefers missing some redundant conditions to warning about common defensive or compatibility patterns. ## Avoiding false positives ### Separate likely mistakes from more opinionated checks Types assignable to `int`, including `bool`, use the strict rule. So do conditions whose outcome is fixed by short-circuit evaluation even though their inferred value type has ambiguous truthiness, and tests containing walrus expressions. Other values with fixed truthiness use the default rule. This keeps checks of ordinary boolean/integer flags quiet by default, because these are extremely common and it is difficult to distinguish deliberately constant flags from mistakes: ```python DEBUG = False if DEBUG: # Only reported by redundant-condition-strict. print("debugging") ``` The strict rule is a sibling of the default rule: it handles a separate set of expressions rather than reporting the same expressions more aggressively. ### Distinguish a condition's outcome from its value type Short-circuit evaluation can establish a fixed outcome even when the expression's value type does not: ```python def check(value: object): if value and False: # Always false; reported by redundant-condition-strict. print("unreachable") ``` The condition fails whether `value` is truthy or falsy. However, saving `value and False` to a variable and testing that variable later is different: the saved value could be the original object, whose `__bool__` result may change between calls. The redundant-condition checks use short-circuit truthiness APIs introduced in https://github.com/astral-sh/ruff/pull/28082 for direct conditions, and value-type truthiness for tests of computed values. This also handles chained comparisons whose intermediate results are objects with mutable truthiness. ### Recognize explicitly constant tests Both rules exempt direct boolean, integer and `None` literals in the AST, such as `if False:`, `if 0:`, `while True:`, `while 1:`, and `assert None`. These spellings are strong evidence that the constant truthiness is deliberate. A name _inferred_ as `Literal[False]` is different: its value may not be apparent where it is tested, so it remains eligible for the strict rule. ### Treat walrus expressions as evidence of intentional side effects An always-truthy operand can be useful because evaluating it assigns a value: ```python if should_continue() and (message := "continuing") and is_ready(): print(message) ``` The middle operand uses the strict rule, so it does not warn by default. We does not attempt to classify arbitrary side effects. For example, `if items.append(value) or fallback:` can still trigger the default rule because `append` returns `None`. An `and`/`or` expression used to compute a value (rather than one that is used directly in an `if` test or similar), such as `result = items.append(value) or fallback`, is not flagged by either rule. ### Follow the origins of environment-dependent conditions Both rules exempt compatibility checks involving `sys.version_info`, `sys.platform`, `os.name`, and `TYPE_CHECKING`. A condition being constant for the configured environment does not make it redundant across the environments supported by the project. The exemption also follows names and attributes through their definitions, including aliases and imports across modules: ```python import sys IS_WINDOWS = sys.platform == "win32" LINE_PREFIX = "\n" if IS_WINDOWS else "" if LINE_PREFIX: # Exempt even though its truthiness is known on this platform. print(LINE_PREFIX) ``` The traversal follows assignment values, augmented assignments, walrus bindings, loop and comprehension iterables, context-manager expressions, and the subjects of captured `match` patterns. This lookup is deliberately not flow-sensitive: if any resolved definition depends on one of these symbols, the use is exempt. This is so that we err on the side of avoiding false positives. The shared definition-resolution machinery from #28032 allows this traversal during inference without requesting completed inference of the same scope. Name lookups are cached per scope and name; attribute lookups are cached per receiver type and attribute name. Definition traversal has its own Salsa query boundary and handles cyclic aliases, so repeated conditions can share the provenance analysis. ### Preserve defensive assertions and exhaustive dispatch Defensive boolean/integer assertions such as `assert isinstance(value, int)` remain useful at runtime even when `value` is annotated as `int`, since the runtime does not enforce type annotations. These are therefore exempt from both rules. Non-boolean mistakes such as `assert function` (where the user meant `assert function()`) are still reported by the default rule. A complete assertion whose value type has ambiguous truthiness but whose outcome is fixed by short-circuit evaluation remains eligible for the strict rule. For `if` and `elif` statements, the strict rule also recognizes defensive exits. An always-false condition is exempt when its body ends in a `raise`, an assertion that might fail, a call returning `Never`, or a return assignable to `NotImplementedType`: ```python def increment(value: int) -> int: if not isinstance(value, int): raise TypeError("expected an int") return value + 1 ``` For an always-true condition, the same heuristic examines an immediately following `else` suite, or the remainder of the surrounding suite when there are no later clauses. This accommodates exhaustive dispatch followed by `assert_never`, and early-return dispatch followed by a defensive exception. These defensive-exit exemptions apply to boolean/integer conditions and conditions requiring short-circuit analysis. An uncalled function is still suspicious even when an otherwise unreachable branch raises. ### Check compound conditions once In `result = flag and function`, Python does not test the truthiness of the final operand: it simply returns that value if evaluation reaches it. The rule therefore does not flag `function`, even though it is an always-truthy object in a boolean expression. In `if flag and predicate:`, the surrounding `if` does test the truthiness of `predicate`, so the rule reports the uncalled function even though the complete condition has ambiguous truthiness. Unlike `and`/`or` expressions used to compute values, `not` explicitly tests its operand's truthiness even when it used to computer a value, so `not` expressions are checked even outside the context of `if`/`while`/`elif`/`assert` tests. For compound conditions, the redundant-condition checks visit operands before deciding whether to report the complete expression. Reporting an uncalled function in `if not function:` suppresses a second duplicate diagnostic on the `not function` expression as a whole. Boolean/integer operands and operands requiring short-circuit analysis are instead suppressed so that the complete condition can be reported once. This applies consistently to statement conditions, conditional expressions, and comprehension filters. Boolean tests inside value expressions, such as `if consume(not function):`, are checked independently. Tests in nested scopes are checked when those scopes are inferred. Neither rule runs in stub files or files excluded from checking. Diagnostic and provenance analysis is skipped entirely when both rules are disabled. ## Diagnostics and fixes Special-case diagnostics are provided to help explain some of the more common errors we see in the ecosystem: an uncalled function or method being always truthy, a fixed-length tuple being always truthy or always falsy, a `TypedDict` always being truthy due to the presence of `Required` fields, a `@final` class without `__bool__` or `__len__` being always truthy, or an unevaluated generator being always truthy. For simple function and method references, the diagnostic carries a call fix. A parameterless signature gets an unsafe `()` fix; signatures with parameters get a display-only `(...)` suggestion. Generator diagnostics suggest `any()` and carry a display-only wrapping fix when the standard `any` builtin is known not to be shadowed, including by a custom `__builtins__.pyi`. These fixes are deliberately not classified as safe: calling a function or consuming a generator can change runtime behavior, and the intended correction may be different. ### Default-rule diagnostics <details> <summary>Uncalled function</summary>  </details> <details> <summary>Uncalled method</summary>  </details> <details> <summary>Generator: suggest <code>any()</code></summary>  </details> <details> <summary>Tuple with a fixed length</summary>  </details> <details> <summary>Tuple with a minimum length</summary>  </details> <details> <summary>Empty tuple</summary>  </details> <details> <summary>Nonempty string literals</summary>  </details> <details> <summary>Empty string</summary>  </details> <details> <summary><code>None</code></summary>  </details> <details> <summary><code>TypedDict</code>: required fields and their declarations</summary>  </details> <details> <summary>Final class without <code>__bool__</code> or <code>__len__</code></summary>  </details> <details> <summary>Enum: implicit finality</summary>  </details> ### Strict-rule diagnostics These examples enable `redundant-condition-strict` explicitly. <details> <summary>Indexing <code>bytes</code> returns <code>int</code></summary>  </details> <details> <summary>Comparing <code>str</code> with <code>bytes</code></summary>  </details> <details> <summary>Length comparison: explain the fixed tuple length</summary>  </details> <details> <summary>Comparison: omit an obvious literal's type annotation</summary>  </details> ## Implementation The semantic index records the outermost boolean tests in each scope, so one check owns the diagnostics for a complete condition and its subexpressions. A shared checker separates classification, context exemptions, and duplicate suppression from diagnostic rendering. The main implementation is in `types/infer/builder/redundant_conditions/mod.rs`; its `diagnostic.rs` submodule constructs messages and fixes, and `exemptions.rs` handles environment provenance and defensive exits. |
||
|
|
53a94487e7 |
[ty] Infer variance through recursive protocols (#28077)
## Summary
We now infer and validate variance through direct, mutual, and expanding
recursive protocol references. A recursive member no longer suppresses
the variance mismatch in this protocol:
```python
from typing import Protocol, TypeVar
T_co = TypeVar("T_co", covariant=True)
class Sink(Protocol[T_co]): # error: should be contravariant
def write(self, value: T_co) -> None: ...
def next(self) -> "Sink[T_co]": ...
```
We separate constructing variance equations from evaluating them.
Recursive references name another parameter’s equation instead of
expanding its definition, so even references like `P[list[T]]` produce a
finite problem.
To validate a declaration, we solve mutually dependent parameters
together, starting at bivariance and updating until the results stop
changing. This prevents a protocol’s declared variance from serving as
evidence for its own correctness. Declarations outside that recursive
group remain authoritative. Dependencies also respect argument erasure:
an alias that ignores its type argument does not create a recursive
dependency through that argument. Ordinary type inference continues to
honor declared variance, including for unused parameters.
The symbolic terms and fixed-point iteration follow the general approach
described in the [Rust compiler’s variance-inference
documentation](https://rustc-dev-guide.rust-lang.org/variance.html#the-algorithm),
adapted here to validating Python protocol declarations.
This also enables structural variance inference for recursive PEP 695
protocols, including invariance from writable attributes. Recursive type
aliases and descriptor setters whose accepted values cannot be
represented by a single type remain deferred.
|
||
|
|
6e6622ca53 |
[ty] Optimize recursive protocol checks for nested type variables (#28257)
Binding inherited recursive protocol methods could repeatedly expand the protocol interface when a receiver's type arguments contained nested type variables, such as `Iter[T | Iterable[T]]`. Recognize those variables when the nominal constraints already mention them, while retaining the structural implication check before skipping recursive requirements. On [pyochain at `4b482210`](https://github.com/OutSquareCapital/pyochain/tree/4b482210241b095bbd1968b8f860a68f3d291746), the reduced `Iter(base).chain(*others)` call completes in 0.22 seconds instead of exceeding eight seconds. The full repository now completes in 4.54 seconds instead of exceeding a 20-second limit, using an optimized debug build. Fixes [astral-sh/ty#4269](https://github.com/astral-sh/ty/issues/4269). ## Test plan - Add mdtests for inherited receiver binding with tuple, union, and aliased type arguments, and for structural inference of a nested variable erased by protocol inheritance. - Add a regression benchmark for overloaded recursive protocol methods on a nominal receiver with a union containing a type variable. |
||
|
|
321e8e4ef5 |
[ty] Optimize materialized recursive protocol comparisons (#28079)
Comparing explicit receiver types on overloaded recursive protocol methods can repeatedly expand materialized protocol specializations until ty overflows its stack. This extends the non-recursive-member shortcut to eligible materialized assignability comparisons, avoiding that expansion while preserving inference constraints. For two specializations of the same protocol, the shortcut checks the non-recursive target requirements against the complete source interface. It skips recursive requirements only when those constraints mention every type variable in both specializations, including through aliases, and imply the nominal type-argument relation. Opposite top-to-bottom materializations and comparisons that cannot establish this proof retain the full structural path. On main, the added benchmark overflows the stack. With this change it completes in about 10 ms in a profiling build. Part of [astral-sh/ty#4269](https://github.com/astral-sh/ty/issues/4269). ## Test plan - Overloaded recursive protocol methods with tuple-specialized receivers and a gradual fallback terminate and preserve the callback's return type. - Generic inference retains evidence supplied only by recursive members for both top and bottom materializations, including aliased parameters and variables on the source side of contravariant comparisons. - Source members that contain the protocol remain available when the corresponding target requirement is non-recursive. - Assignability and constraint inference reject top-to-bottom comparisons when a fixed `Any` in a recursive method becomes an incompatible return requirement. - An added benchmark checks the expanding recursive-overload case. |
||
|
|
700421c2ab |
[ty] Reject circular type alias definitions (#28140)
## Summary
Previously, we accepted circular `TypeAliasType` definitions and aliases
that include themselves as union members. We now report
`cyclic-type-alias-definition` for these cases, while continuing to
allow recursion through containers and other concrete types.
```python
from typing import TypeAliasType
# Before: no error. After: cyclic-type-alias-definition.
Direct = TypeAliasType("Direct", "Direct")
# Before: no error. After: cyclic-type-alias-definition.
type IntOr = int | IntOr
# Before and after: no error.
type Tree = int | list[Tree]
```
We follow references through aliases and unions, stopping when recursion
occurs inside another type, such as `list[Tree]`. For generic aliases,
we follow only the type arguments exposed by the alias's definition.
This lets us distinguish an actual cycle from a finite expression like
`Identity[Identity[int]]`, or an unused recursive argument like
`Constant[Cycle]` when `Constant[T]` is defined as `int`.
The checks reuse cached summaries across alias definitions. Checking a
chain of 8,192 aliases takes 0.092 seconds, compared with 0.087 seconds
on the base branch, using the median of five runs with matching debug
builds.
This moves
[`aliases_typealiastype`](https://github.com/python/typing/blob/cf943ccbea5596ef969eec6e2260097ff697b7ba/conformance/tests/aliases_typealiastype.py)
and
[`aliases_type_statement`](https://github.com/python/typing/blob/cf943ccbea5596ef969eec6e2260097ff697b7ba/conformance/tests/aliases_type_statement.py)
from Partial to Pass, adding three missing errors in the former and one
in the latter. The other 143 conformance results are unchanged.
<details>
<summary>Case analysis</summary>
Mypy 2.1.0, pyright 1.1.410, and pyrefly 1.3.0-dev.1 (with the default
preset) already report the four required errors that we were missing.
All three reject direct, mutual, and union cycles; the differences below
concern additional generic alias cases.
Changing a recursive reference's type argument does not make a union
cycle valid. All four checkers reject this definition, while accepting
recursion through a container:
```python
# ty, mypy, pyright, pyrefly: error.
type Cycle[T] = T | Cycle[str]
# ty, mypy, pyright, pyrefly: OK.
type Tree[T] = T | list[Tree[T]]
```
Recursion through a container remains valid when the type arguments
grow. In `Repeated` below, expanding the aliases outside `list` reaches
`int`, so there is no circular definition. Ty and pyright accept it;
pyrefly reports a cyclic self-reference. Mypy rejects the underlying
`Recursive` definition because it does not support this pattern of
growing type arguments, and also reports an error on `Repeated`.
```python
# ty, pyright, pyrefly: OK.
# mypy: error; growing type arguments in recursive aliases are unsupported.
type Recursive[T] = T | list[Recursive[list[T]]]
# ty, pyright: OK. Mypy, pyrefly: error.
type Repeated = Recursive[Recursive[int]]
```
In contrast, substituting `Cycle` for `T` exposes `Cycle` itself as a
union member. Ty, pyright, and pyrefly reject this. Mypy rejects
`Recursive` as above, so it cannot provide a useful comparison for this
use of the alias:
```python
type Recursive[T] = T | list[Recursive[list[T]]]
# ty, pyright, pyrefly: error.
type Cycle = Recursive[Cycle]
```
These results also hold for equivalent definitions using
`TypeAliasType`.
A generic alias that returns its argument cannot make a circular
definition valid. Ty and pyrefly reject this cycle, but pyright accepts
it. Mypy did not finish checking the isolated example within 20 seconds:
```python
type Identity[T] = T
# ty, mypy, pyright, pyrefly: OK.
type Repeated = Identity[Identity[int]]
# ty, pyrefly: error. Pyright: OK. Mypy: timed out.
type Cycle = Identity[Cycle]
```
</details>
|
||
|
|
f5e6c6ae8f |
[ty] Avoid repeated traversal of shared alias arguments (#28147)
Searching generic alias arguments for `Self` or a type variable starts a fresh type walk for each argument. Shared nested specializations are therefore visited repeatedly, which can make method binding take exponential time even when its annotations contain no `Self`. Use a shared visitor implementation for both searches, with one recursion guard per search. It visits explicit alias arguments, including arguments unused by the alias body, without evaluating alias bodies or other lazy attributes. Different specializations of the same alias remain distinct. Follow-up to #28117. ## Test plan Add mdtests for `Self` used only in an aliased parameter, including accepted and rejected arguments, and nested uses of the same alias in an inherited method. Simplify the protocol fixtures while retaining separate method and property cases for structural `Self` binding. A minimized example with 32 levels of shared alias arguments completes in about 40 ms; the prior implementation hit a 12-second timeout in the same debug-build setup. |
||
|
|
edd48cc5f6 |
[ty] Bind Self through generic type aliases (#28117)
## Summary
ty incorrectly rejects structural protocol implementations when `Self`
appears as an argument to a generic type alias:
```python
type Identity[T] = T
class Cloneable(Protocol):
def clone(self) -> Identity[Self]: ...
class Concrete:
def clone(self) -> Identity[Self]:
return self
```
`Self` binding uses a preliminary check to avoid applying a type mapping
when a type does not contain `Self`. Because type alias bodies are lazy,
this check did not inspect the alias specialization and therefore missed
the `Self` argument in `Identity[Self]`.
Inspect generic type alias arguments when checking for `Self`, without
evaluating the alias body. The existing type mapping can then bind
`Self` normally in method parameters and returns, property types, and
attribute annotations.
Fixes astral-sh/ty#4409.
## Test Plan
- Added mdtests for binding aliased `Self` in bound method parameters,
return types, and attribute annotations.
- Added protocol mdtests covering aliased and direct structural method
implementations and property return types.
- Ran the full `ty_python_semantic` test suite.
- Ran Clippy with all targets and features and warnings denied.
- Ran the applicable repository hooks.
|
||
|
|
4125782a78 |
[ty] Optimization: reject impossible eager protocol comparisons early (#28081)
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. |
||
|
|
3f5e494bd2 |
[ty] Only treat recursive types with unbounded specializations as fallback cycles (#27538)
## Summary Fixes https://github.com/astral-sh/ruff/pull/26503#discussion_r3607065111 Approach #26989 didn't work. This would be a more legitimate approach. In #26503, regardless of what the recursive type was, if it appeared again with a different specialization during the visit of `CycleDetector`, there was a risk that the visit would not stop, so a `Cycle` state was returned immediately. This is OK for the growing pattern, but misses the saturating pattern, as shown below. ```python type Growing[T] = T | Growing[list[T]] type Saturating1[T, U] = T | Saturating1[U, T] type Saturating2[T] = tuple[T] | tuple[T, Saturating2[int]] type Saturating3[T] = tuple[T, Saturating3Helper[list[T]]] type Saturating3Helper[U] = tuple[U, Saturating3[int]] ``` Think of this as a graph problem. The type parameter of each definition is used as a node, and the following edges are created from the type parameter of the recursive reference. * Direct: Type parameters are passed as is. * Nested: A type parameter is passed inside another type. * Edgeless if no type parameters appear If there is even one nested edge in the directed cycle containing the root formal type argument, it is determined that the specialization can increase infinitely. e.g. ```python type A[X, Y] = A[list[Y], X] # A.Y -> A.X Nested # A.X -> A.Y Direct # => growing ``` ```python type Left[A, B, C, D] = Left[B, C, D, None] # Left.B -> Left.A Direct # Left.C -> Left.B Direct # Left.D -> Left.C Direct # => saturating ``` ```python type A[X, Y] = A[list[Y], None] # A.Y -> A.X Nested # => saturating (no cycle) ``` ## Test Plan mdtest updated |
||
|
|
f41e263298 |
[ty] Validate generic protocol variance (#27531)
## Summary Follow-up to #27534. We now validate explicitly declared generic protocol variance against its structural interface: ```python from typing import Protocol, TypeVar T = TypeVar("T") class Source(Protocol[T]): # error: [invalid-protocol] def read(self) -> T: ... ``` A type variable appearing only in a return position must be covariant, while writable protocol attributes must remain invariant. We derive both declared and inferred variance from the same member read/write capabilities already used for structural compatibility, including inferred legacy and PEP 695 protocol parameters: ```python class Writable[T](Protocol): _value: T def overwrite(value: Writable[object]) -> None: value._value = object() def unsound(value: Writable[int]) -> None: overwrite(value) # error: [invalid-argument-type] ``` For now, I've limited this to the easier cases, so recursive interfaces, custom descriptors with unrepresentable setter domains, generic defaults, and inherited or malformed headers are unchanged. |
||
|
|
80bca70e09 |
[ty] Fix Self binding in ParamSpec protocols (#28016)
Specializing a protocol's `ParamSpec` could leave a method's `Self` return type unbound, incorrectly rejecting structural implementations. This change restores `Self` binding for both instance and class methods, including assignments to `type[Protocol]`. Preserve the enclosing signature's definition when expanding a concrete `ParamSpec`. The definition provides the binding context for `Self` and other receiver type variables; the substituted parameter list does not provide a replacement method definition. Parameter and overload-source metadata remain unchanged. Fixes https://github.com/astral-sh/ty/issues/4369. ## Test plan Add mdtests for `Self`-returning instance and class methods in specialized `ParamSpec` protocols. Cover empty and concrete parameter lists, instance and class-object assignments, and rejection of implementations returning an unrelated type. |
||
|
|
2d942cc99a |
[ty] Recognize ABC metaclass methods on protocols (#27897)
Valid calls such as `collections.abc.Mapping.register(...)` currently produce missing-attribute errors. Using `register` as a class decorator can also hide the registered class’s members and generic parameters, causing further false positives and negatives. This PR gives protocol classes declared in source or ordinary `.pyi` files the metaclass `typing._ProtocolMeta`, which derives from `ABCMeta`. That makes ABC methods available and preserves the types of registered classes. It also lets ty report incompatible custom metaclasses. Typeshed’s standard-library stubs need a narrow compatibility exception: they sometimes list `Protocol` bases that the runtime class does not inherit. When those bases do not select a custom metaclass, ty uses `ABCMeta` for attribute lookup but does not let that inferred metaclass create artificial inheritance conflicts. This applies to bundled or configured typeshed, not to other `.pyi` files. An explicitly chosen custom metaclass continues to constrain subclasses. Known built-ins retain their actual `type` metaclass. Mypy applies a similar permissive fallback more broadly; this PR limits the exception to typeshed. Fixes https://github.com/astral-sh/ty/issues/1204. ## Ecosystem results The [current ecosystem run](https://github.com/astral-sh/ruff/actions/runs/32385816515/attempts/1) removes missing-`register` errors in pandas, ppb-vector, Jinja, Spack, and Ibis, plus two spurious metaclass conflicts in Spack’s legacy `typing_extensions`. All 294 Ibis changes follow from recovering registered classes’ members and generic parameters. The added diagnostics expose existing annotation gaps, deliberately invalid tests, and the known [virtual ABC subclass limitation](https://github.com/astral-sh/ty/issues/2391). The beartype library has an [old compatibility workaround](https://github.com/beartype/beartype/blob/d6c056225f2e5632ea72006b43ffb066bd9a2c6b/beartype/typing/_typingpep544.py#L73-L79) for the fact that `_ProtocolMeta` used to be missing from typeshed; it substitutes `ABCMeta` under `if TYPE_CHECKING`, so it now produces a metaclass conflict. We accept this false positive: typeshed now declares `_ProtocolMeta`, and beartype can remove the workaround and derive from `type(Protocol)` directly. ## Test plan - Cover protocol metaclasses, bundled and custom typeshed, and registration decorators that preserve generic classes. - Check compatible and conflicting metaclasses, built-in collections, and inheritance through ordinary and dynamically created classes. - Protect subclass-type bounds, class-namespace attributes, quoted unions, and dataclass-transform inheritance. |
||
|
|
4eb2045b23 |
[ty] Preserve type-variable order when reloading constraints (#27904)
## Summary Reloading an owned constraint set could reverse its type-variable ordering, causing successive loads to alternate between two equivalent representations of the same constraint. A generic protocol with a nested explicit receiver could consequently exhaust Salsa's cycle iterations during constructor inference. Preserve the saved order of referenced type variables before rebuilding constraints. Existing destination IDs remain unchanged, and wholly unused type variables are not carried into the new builder. Retain support records for constraints kept only as source-order metadata so those variables can also be restored correctly. Closes https://github.com/astral-sh/ty/issues/4337. ## Test plan - Add unit coverage for repeated lower-bound, upper-bound, and equality-constraint round trips; discarded type variables; loading into an existing storage overlay; and retained quantified-constraint ordering. - Add a protocol mdtest that infers a constructor's type argument from a generic protocol with a nested explicit receiver and another generic method, asserting that checking terminates and infers `Implementation[int]`. - Compare the full mdtest suite under reversed and XOR-permuted constraint orderings against unchanged main; existing order-sensitive failures are identical. |
||
|
|
680cce48b6 |
[ty] Optimize inherited recursive protocol comparisons (#27922)
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. |
||
|
|
1e69d7a56d |
[ty] Preserve source protocol members and classify finite aliases (#27772)
This is the first prerequisite for fixing the performance issues in astral-sh/ty#4269. It makes ty's existing shortcut for comparing recursive protocols more accurate, without adding the later performance optimizations. ## Keep the methods needed for comparison A recursive protocol can send the type checker back through the same requirements repeatedly. To avoid that, ty can first compare the requirements that do not refer back to the protocol. The problem was that it removed recursive-looking members from *both* types being compared. A member of the actual type can mention the protocol even when the corresponding requirement does not, so removing it loses information needed to decide whether the types are compatible. For example: ```python from __future__ import annotations from typing import Protocol class Consumer[T](Protocol): def consume(self, value: T | int) -> None: ... @property def child(self) -> Consumer[T]: ... def extract[T](consumer: Consumer[T]) -> T: raise NotImplementedError def check(value: Consumer[Consumer[int]]) -> None: reveal_type(extract(value)) # Before: Consumer[int] # After: Consumer[int] | int ``` Here, the actual `consume` method accepts `Consumer[int] | int`. Its annotation mentions `Consumer`, so the old shortcut could discard the method and infer only `Consumer[int]` from the class's type arguments. Keeping the method available preserves the additional `int` possibility. This PR filters only the requirements of the expected protocol, while keeping every member of the actual type available to satisfy those requirements. It also uses ordinary matching when the expected protocol has no recursive requirements, even if the actual type contains a nested use of the same protocol. ## Distinguish repeated aliases from recursion ty tries to compare simple protocol members before members that can lead back into another protocol comparison. Previously, any type alias caused a member to be put in the potentially recursive group, even when the alias was just another name for `int`. The new traversal follows alias definitions before making that decision. Reusing an ordinary alias does not itself create a cycle: ```python type Identity[T] = T # This expands completely to int. type Example = Identity[Identity[int]] ``` But an actually recursive alias can keep changing its type arguments as it expands: ```python type Growing[T] = T | Growing[list[T]] # Growing[int] leads to Growing[list[int]], then # Growing[list[list[int]]], and so on. ``` For a recursive alias, the traversal stops when it reaches a definition it is already expanding, even if the type arguments have changed. Ordinary alias applications remain distinct, so nested uses such as `Identity[Identity[int]]` are still recognized as non-recursive. ty can answer this question without expanding the rest of a protocol's members. ## Test plan The added protocol mdtests cover: - A non-recursive expected protocol whose actual type contains a nested use of that protocol. - Recursive protocol members that contribute the full `Consumer[int] | int` inference shown above. - Nested applications of a non-recursive generic alias that must still contribute to type inference. - A recursive alias whose type arguments grow, checking that comparison terminates and still rejects an incompatible assignment. |
||
|
|
ce46a36be7 |
[ty] Simplify generic protocol inference (#27819)
Generic protocol inference still treated some arguments as callable signatures even after class objects gained structural inference in #27812. That duplicated the protocol logic and could miss type-variable evidence from members other than `__call__`. Use one structural-constraint branch for protocol formals, preserving the TypedDict-union optimization. Remove the protocol-specific `__call__` path and its unused helper. This also allows module attributes and ordinary function attributes to contribute to generic protocol inference, and preserves type-variable evidence hidden behind type aliases. Stacked on #27812. ## Test plan Added mdtests for inferring a protocol type argument from a module attribute and from a function's `__name__` alongside `__call__`. Added coverage for inference and type-variable bounds through both PEP 695 and `TypeAliasType` aliases. Simplified the class-method regression fixture to use PEP 695 syntax. Existing coverage continues to exercise class objects, callable overloads, ParamSpec, TypeVarTuple, TypedDict unions, and enum iteration. --------- Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com> |
||
|
|
1d5d4c52da |
[ty] Infer generic protocols from class objects (#27812)
## Summary Passing a class object to a generic protocol parameter could leave the protocol's type arguments as `Unknown`, even when its attributes or methods supplied enough information to infer them. Ordinary instance arguments and unions already used structural constraints, but individual class objects fell through to inference that only considered `__call__`. Use the existing structural constraint machinery for class literals, specialized generic classes, and `type[C]` arguments. This preserves the class object's own interface and also fixes `list(EnumClass)` inferring `list[Unknown]`. Fixes https://github.com/astral-sh/ty/issues/4291 ## Test plan Added mdtests for inference through plain class attributes, class methods, static methods, ordinary-method protocols, specialized generic class objects, and unions of class types. Callback regressions cover preserving `T` when passing `type[T]` and inferring from a data member alongside `__call__`. The tests also retain instance behavior and rejection of an incompatible return type. Updated the enum iteration test to expect the precise member type. ### Ecosystem The ecosystem report includes a new `invalid-assignment` diagnostic in [Scrapy's telnet test](https://github.com/scrapy/scrapy/blob/488a762d7173922190ea027e0fb6f6d9d3b59880/tests/test_extension_telnet.py#L46), which replaces a zero-argument bound method with `dict`. This PR correctly infers `TelnetConsole` where the result was previously `Unknown`, revealing an orthogonal, pre-existing limitation in ty's instance-method assignment checking. The directly typed assignment is rejected on both the base and PR revisions; the inference change does not introduce that restriction. Compatible class-level method replacement was addressed in [#26158](https://github.com/astral-sh/ruff/pull/26158), while instance-method replacement remains separate work related to [ty#350](https://github.com/astral-sh/ty/issues/350). This is just better type inference exposing an unrelated issue, so we accept it for this PR. Other ecosystem changes are desirable improved inference. |