## Summary
ty accepted `Impossible(value=1)` for a dataclass with a required
`value: Never` field, even though it inferred `Never` when reading the
field.
Looking up `__set__` on `Never` yields `Never`. Since ty treats `Never`
as callable with arbitrary arguments, it inferred `Unknown` for the
setter's value parameter. Here, we simply extend a special-case that was
previously only active for dynamic types. This is something that's very
common in ty: almost all special-cases for dynamic types apply to
`Never` as well.
fixesastral-sh/ty#5140
## Summary
attrs `field()` is overloaded. There are (valid) `field` calls that can
lead to ambiguous overloads. In the example in astral-sh/ty#5134, this
is caused by passing in a converter which takes an unspecialized
`Attribute` argument (i.e. `Attribute[Unknown]`). With the change here,
instead of "giving up", we combine/merge the result of ambiguous
`field()` calls by merging their `Field` instances if the agree in
metadata (`kw_only`, `init`, `converter`, ...).
I believe I've seen cases of this in other dataclass-transformer
libraries as well, which is why I added a test in `dataclass_transform`
as well.
Closesastral-sh/ty#5134
## Summary
Passing a dataclass field with `init=False` to `copy.replace` raises a
`TypeError` at runtime. ty now excludes these fields from the signature
of the synthesized `__replace__` method.
```py
from copy import replace
from dataclasses import dataclass, field
@dataclass
class User:
name: str
id: int = field(init=False, default=0)
user = User(name="Alice")
replace(user, name="Bob") # ok
replace(user, id=42) # ty now reports an unknown argument here
```
This also applies to attrs classes, Pydantic dataclasses and other
classes that use `dataclass_transform`.
Currently some synthesized methods handle `Self` differently than normal
methods: instead of treating `Self` as an inferrable typevar in the
generic context of the synthesized methods, they eagerly replace `Self`
with the concrete defining class.
The code implementing this eager substitution was a little too broad,
and could also catch method aliases, in cases like this (real-world
example):
```py
from collections.abc import Awaitable
from typing import Any, Literal, Protocol, overload, reveal_type
class AsyncClient(Protocol):
_is_async_client: Literal[True]
class SyncClient(Protocol):
_is_async_client: Literal[False]
class Commands:
@overload
def incrby(self: SyncClient, name: str) -> int: ...
@overload
def incrby(self: AsyncClient, name: str) -> Awaitable[int]: ...
def incrby(self: Any, name: str) -> int | Awaitable[int]:
raise NotImplementedError
incr = incrby
class Redis(Commands):
_is_async_client: Literal[True] = True
def f(r: Redis) -> None:
reveal_type(r.incrby("k")) # Awaitable[int]
reveal_type(r.incr("k")) # expected Awaitable[int]
```
On main, we incorrectly categorize the `incr` alias as a synthesized
method, so we prune overloads correctly for `r.incrby` calls but not for
`r.incr` calls.
This PR makes `Self` handling consistent across synthesized and normal
methods, which fixes these calls to method aliases, too.
Synthesized named-tuple and dataclass methods now register `Self` in
their generic contexts and connect field annotations to that inferable
type variable. This lets them use ordinary call inference. Anonymous
decorator results retain a temporary fallback for
[ty#3186](https://github.com/astral-sh/ty/issues/3186) when a receiver
type variable has no generic context. Specialized protocol receivers and
constrained receivers retain their existing handling.
Pydantic constructor receivers are positional-only, matching the runtime
signature and keeping fields named `self` separate from the receiver.
Fixes astral-sh/ty#4715.
## Test plan
Ran the classmethod, constrained-TypedDict, and union-receiver examples
from the review of #26861 against this implementation. Aliased
classmethods preserve their return types and subclass `Self`;
constrained TypedDict subscription is accepted; the invalid
union-receiver call retains `no-matching-overload` diagnostics instead
of becoming non-callable.
## Ecosystem report
Analyzed
[`6052e4fb1c`](https://github.com/astral-sh/ruff/commit/6052e4fb1c6f941ead46f4a103810802dbe14e38).
Most changes update existing receiver counts; alias return inference
improves, and borrowed methods and classmethod aliases enforce their
receiver constraints. Additional diagnostics expose an existing
native-function binding limitation. All public ecosystem changes are
accounted for and do not block this PR. [Full ecosystem
analysis](https://github.com/astral-sh/ruff/pull/29341#issuecomment-6157452697).
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.
Fixesastral-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)
## Summary
`ty check` panics with `too many cycle iterations` on Rowstile’s
[condition
parser](https://github.com/rowstile/rowstile/blob/617db6b1f3953fd3d6acb8a62ad4b6a6e6a043b4/core/authzlib/conditions.py#L82-L98).
The parser represents nodes as a union of named tuples. Two of them are
enough to reproduce the panic.
```python
from typing import NamedTuple
class IsNull(NamedTuple):
item: "Node"
class Bool(NamedTuple):
items: tuple["Node", ...]
Node = IsNull | Bool
```
While inferring `Bool.items`, ty checks whether the metaclass or a base
class supplies a dataclass transform. Resolving those classes builds the
tuple base for `Bool`. Since `items` is its only field, that base is
`tuple[tuple[Node, ...]]`, and building it requires inferring `items`
again.
We now use bare `tuple` when selecting the metaclass or searching the
method resolution order for a dataclass transform. Indexing still uses
the specialized tuple base, so for `node: Bool`, `node[0]` has type
`tuple[Node, ...]`.
## Summary
When a dataclass has a field declaration with a union annotation like
the following, ty speculatively uses each union element individually as
type context to infer a type for `field(..)`.
```py
def returns_any() -> Any: ...
@dataclass
class Entry:
value: str | None = field(default_factory=returns_any, kw_only=True)
```
When both inference paths succeed, ty infers the field call as
`Field[str] | Field[None]` which then prevents proper recognition of
field metadata like `kw_only`. Here, we avoid this speculative inference
and use the full `str | None` type as context to end up with `Field[str
| None]` in this example.
Fixes https://github.com/astral-sh/ty/issues/4986.
Co-authored-by: @carljm
## Test Plan
Added regression test
Co-authored-by: Carl Meyer <carl@astral.sh>
Rename the method, attribute, property, and mutable override rules to
`incompatible-…-override`. The old names remain aliases in configuration
and inline suppressions:
| Before | After |
|---|---|
| `invalid-method-override` | `incompatible-method-override` |
| `invalid-attribute-override` | `incompatible-attribute-override` |
| `invalid-property-type-override` | `incompatible-property-override` |
| `invalid-mutable-override` | `incompatible-mutable-override` |
A follow-up PR will split `invalid-method-override` into two rules.
Fixesastral-sh/ty#2001.
---------
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
## Summary
Users can now suppress an attribute error that affects only some union
members and still catch names that are missing from every member. For
example, both lines below previously reported `unresolved-attribute`:
```python
def clean(value: str | int) -> str:
value.stirp() # missing-attribute: neither str nor int has stirp
return value.strip() # missing-union-attribute: str has strip, int does not
```
The motivation is that a project adopting ty may want `value.strip()` on
`str | None` to only warn while a typo remains an error-severity
diagnostic.
Both rules default to errors. The same distinction applies to optional
values such as `str | None` and to attribute deletion. Attributes
defined only conditionally on a class continue to use
`possibly-missing-attribute`.
### Comparison to other type checkers
Pyright distinguishes between `reportOptionalMemberAccess` (which is
specifically for unions with `None`) and `reportAttributeAccessIssue`,
which is for all other unions. mypy, meanwhile, distinguishes between
`union-attr` (which is an error code for all attribute-access errors on
union types) and `attr-defined` (which is an error code for all
attribute-access errors on non-union types). So this new split doesn't
_exactly_ align with either precedent -- but I _do_ think it's probably
the most useful split we can do, and it's the one that makes the most
sense _a priori_ in my opinion.
### Compatibility
`unresolved-attribute` remains an alias for `missing-attribute` in
configuration and inline ignores. To preserve a setting such as
`unresolved-attribute = "warn"` for both cases, also set
`missing-union-attribute = "warn"`. On an access that fails for only
some union members, replace `# ty: ignore[unresolved-attribute]` with `#
ty: ignore[missing-union-attribute]`. Tools that consume diagnostic
codes should recognize both new names.
Fixesastral-sh/ty#2839 and fixesastral-sh/ty#2471.
## Test Plan
A comparison with ty 0.0.96 on typeshed-stats, docstring-adder,
sphinx-lint, and typing_extensions found the same messages, locations,
and severities. Eight diagnostics received `missing-union-attribute`
across those four projects (two in sphinx-lint and six in
typing_extensions).
---------
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
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.
Dataclass-like libraries can generate slots by default, but
`dataclass_transform` has no standardized way to declare that default.
This adds `slots_default` as a ty extension, allowing opted-in
transforms to generate slot descriptors that override inherited abstract
properties. Explicit `slots=True` and `slots=False` arguments override
the declared default.
Slot generation uses the effective parameters for decorator, base-class,
and metaclass transforms, including on Python versions before 3.10. The
vendored signatures recognize the extension while retaining checks for
unsupported arguments.
Related to https://github.com/astral-sh/ty/issues/4591. Attrs will need
to opt in through its annotations before this addresses the reported
case without an explicit `slots=True`.
## Test plan
Added mdtests cover bare decorators and decorator factories, both
directions of explicit slot overrides, base-class and metaclass
transforms, abstract-property overrides, Python 3.9, and legacy
`__dataclass_transform__` functions accepting the extension through
`**kwargs`.
## Summary
We avoid a cycle-iteration panic when a `dataclass_transform` field
specifier refers back to the resulting decorator:
```python
from typing import dataclass_transform
transform = alias = dataclass_transform(field_specifiers=(lambda: transform,))
```
Cycle recovery now normalizes field specifiers in transform and
decorator metadata, including metadata attached to decorated functions.
Non-recursive field specifiers and transform options remain available
for synthesizing dataclass constructors.
Overloaded field specifiers may describe the same field despite having
ambiguous signatures. If a known-method override resolves the ambiguity,
we should no longer consider the overload to be ambiguous, and avoid
falling back to `Unknown`.
```py
from typing import Any, Literal, overload
from typing_extensions import dataclass_transform
@overload
def field(value: int) -> int: ...
@overload
def field(value: str) -> str: ...
def field(value: Any) -> Any: ...
@dataclass_transform(field_specifiers=(field,))
class Model: ...
def _(value: Any):
class Person(Model):
id: int = field(value)
name: str
# main: (self: Person, id: int = ..., name: str) -> None
# now: (self: Person, id: int, name: str) -> None
reveal_type(Person.__init__)
```
## Summary
Previously, we did not model `__slots__` as instance storage, so slotted
attributes were not recognized consistently and classes without an
instance dictionary could accept arbitrary attribute assignments.
```python
class Counter:
__slots__ = ("value",)
def __init__(self) -> None:
self.value = 0
def increment(self) -> None:
self.value += 1
Counter().extra = 1 # error: [unresolved-attribute]
```
We now represent slots as class descriptors and track instance layouts
through inheritance. This covers literal slot declarations, generic and
annotated slots, explicit `__dict__` and `__weakref__` storage,
dataclass-generated slots, descriptor-based writes, class-namespace
lookup, and incompatible builtin layouts.
Slots participate in attribute inference and enumeration, while invalid
class-body declarations and unsupported writes receive the appropriate
existing diagnostics.
Closes https://github.com/astral-sh/ty/issues/1268.
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.
This PR establishes a new invariant that the set of typevars that are
inferable when calling a generic function is _exactly and only_ the
typevars in the function's `GenericContext`.
Surprisingly, this used to not be the case! The main wrinkle is invoking
the constructor of a generic class. In this case, the class typevars are
also inferable. For the most part, we encode that by adding the class
typevars to the generic context of the constructors. But when those
class typevars have an upper bound that contain _other_ typevars, we
were previously including those other typevars in the inferable set as
well. They shouldn't be; this was a hack to cause us to include those
upper bounds correctly when inferring the specialization. This hack
comes from before we had the new solver available. The new solver is
perfectly capable of expressing cross-typevar relationships, and so as
long as we include the upper bounds as additional constraints, we're
good to go.
This pattern also applies to the `Self` typevar that appears in instance
methods, since those implicitly have an upper bound of the class itself.
If the class is generic, we would therefore include the class typevars
in the inferable set — which is actually _incorrect_, since by this
point we already have a specialization for the class, and its typevars
are no longer inferable.
Closes https://github.com/astral-sh/ty/issues/4303
---------
Co-authored-by: Carl Meyer <carl@astral.sh>
Annotation-only declarations in `.pyi` files act as bindings for
attribute lookup, but they are not dataclass or `NamedTuple` field
defaults. Previously, ty treated those synthetic bindings as defaults,
making required constructor parameters optional and reporting false
`dataclass-field-order` diagnostics when subclasses added required
fields.
Record whether an annotated assignment has a right-hand-side value in
its semantic definition, and use that information when collecting
generated fields from stubs. Only inline assignments, including `= ...`,
count as stub-field defaults. Ordinary Python files and stub attribute
lookup retain their existing behavior.
Closesastral-sh/ty#4265.
## Test plan
- Dataclass mdtests cover inherited required stub fields, constructor
signatures and missing-argument diagnostics, explicit ellipsis defaults,
and legitimate inherited field-order diagnostics.
- Dataclass-transform mdtests cover inherited required stub-model
fields, subclass constructor signatures, and missing arguments.
- `NamedTuple` mdtests distinguish required annotation-only stub fields
from explicit ellipsis defaults and verify constructor calls and
missing-argument diagnostics.
## Summary
Previously, we ignored `kw_only=True` on every dataclass field specifier
when targeting Python 3.9, even though libraries such as `attrs` support
keyword-only fields independently of the standard library:
```python
import attr
@attr.s(auto_attribs=True)
class Base:
optional: float = attr.ib(default=1.0, kw_only=True)
@attr.s(auto_attribs=True)
class Child(Base):
required: str
```
We now restrict the Python 3.10 requirement to `dataclasses.field`,
preserving keyword-only behavior for third-party field specifiers on
earlier Python versions. Inherited keyword-only fields no longer trigger
`dataclass-field-order`, and synthesized constructors retain the correct
argument ordering.
Closes https://github.com/astral-sh/ty/issues/4242.
## Summary
PEP 484's numeric tower means we represent a `float` annotation as the
semantic union `int | float*` and `complex` as `int | float* |
complex*`. We previously rendered those internal unions directly, which
exposed an implementation detail in user-facing output:
```python
def f() -> float:
return 1
reveal_type(f()) # Before: int | float; after: float
```
This change recognizes complete numeric-tower unions during display and
renders them using their canonical annotation spelling, `float` or
`complex`.
The implementation does _not_ preserve explicit unions, e.g., if the
user writes out `int | float`, we still collapse that rather than trying
to preserve it, mostly for simplicity (as per
https://github.com/astral-sh/ty/issues/2184#issuecomment-4345219164).
Closes https://github.com/astral-sh/ty/issues/2184.
## Summary
Reject unrecognized `dataclass_transform` parameters based on this
paragraph in the
[spec](https://typing.python.org/en/latest/spec/dataclasses.html#dataclass-transform-parameters)
(emphasis mine):
> kwargs allows arbitrary additional keyword args to be passed to
dataclass_transform. This gives type checkers the freedom to support
experimental parameters without needing to wait for changes in
typing.py. **Type checkers should report errors for any unrecognized
parameters.**
Since we currently don't do any experiments with unofficial parameters
to `dataclass_transform`, we can just remove `**kwargs`.
Fixes https://github.com/astral-sh/ty/issues/4170.
## Test plan
New Markdown tests.
## Summary
Top-materialize th gradual `DataclassInstance` protocol in the `TypeIs`
return type of `is_dataclass`, so that we can recognize dataclass
instances as being a subtype of that return type.
Fixes https://github.com/astral-sh/ty/issues/4149.
## Ecosystem impact
Looks good!
## Test plan
Updated and added mdtests.
## Summary
We now enforce dataclass constructor field ordering across inherited
fields, including `@dataclass_transform` classes.
```python
from dataclasses import dataclass
@dataclass
class Base:
x: int = 1
@dataclass
class Child(Base):
y: int # error: [dataclass-field-order]
```
Fields inherited from `@dataclass_transform(kw_only_default=True)`
remain keyword-only, and overriding an inherited field with `ClassVar`
removes it from the generated constructor without incorrectly excluding
`InitVar` overrides.
Closes https://github.com/astral-sh/ty/issues/4125.
## Summary
We currently top-materialize `TypeIs` types to work around the fact that
typeshed annotates some standard library functions like `isawaitable`
with a gradual `TypeIs[Awaitable[Any]]` return type. This is problematic
when taken verbatim, since that instructs us to intersect with a gradual
`Awaitable[Any]` type instead of truly selecting *all* awaitables
(`Awaitable[object]`). For example, narrowing `Item | Awaitable[Item]`
with a final `Item` class using `isawaitable` would result in
`Awaitable[Item] & Awaitable[Any] = Awaitable[Item & Any]`, instead of
just `Awaitable[Item]`.
However, the current behavior is problematic for user-defined `TypeIs`
functions, since we don't respect their declared return type.
Here, we fix this by patching typeshed while dropping the
top-materialization. This leads to an unchanged behavior for
standard-library functions like `isawaitable`, `iscallable`, etc, but
respects users annotations for custom `TypeIs` functions:
```py
def is_list(arg: object) -> TypeIs[list[Any]]:
return isinstance(arg, list)
def _(x: object):
if is_list(x):
reveal_type(x) # list[Any], previously: Top[list[Any]]
```
relates to https://github.com/astral-sh/ty/issues/3375
## Ecosystem report
Looks mostly good: Removed false positives, new unused ignore comment
diagnostics
Some expected problems, e.g. with this user-defined function in
beartype, leading to unfortunate types like `((...) -> Unknown) &
~((...) -> Unknown)`, which are technically correct (and could maybe be
simplified), but certainly unintended:
```py
def is_callable_like(value: Any) -> TypeIs[Callable]:
return callable(value)
```
## Conformance results
- One false positive removed, which is expected.
- One new false positive, which looks like it's due to a generic solver
gap.
## Test Plan
Adapted tests
## Summary
Support materialization of class-based protocols via lazy
materialization of attribute types.
- Represent a materialized protocol as its original protocol class plus
its `Top` or `Bottom` polarity, materializing individual read and write
requirements only when they are observed.
- Preserve recursive protocols, nominal inheritance, descriptors,
properties, class variables, and class-object member access without
eagerly rebuilding protocol interfaces.
- Propagate materialized member requirements through structural
relations, generic inference, bounds, constraints, invariance, and
overload resolution.
- Infer constructors using the materialized receiver while preserving
explicit `__new__` return types, custom metaclass returns, and mixed
`Self`/non-instance overloads.
- Fix `dataclasses.is_dataclass` narrowing.
## Test plan
- Add mdtests for top and bottom reads and writes, properties,
descriptors, class variables, class-object access, and nominal versus
structural protocol relationships.
- Cover recursive protocols, recursive structural inference, inherited
and structural generic inference, bounds, constraints, invariant
arguments, overload selection, generic aliases, `Self`, legacy type
variables, and generator delegation.
- Cover constructors that return protocol instances, non-instance
values, custom metaclass values, and mixed overloaded return types.
- Verify `dataclasses.is_dataclass` narrows an impossible branch to
`Never`.
### Ecosystem
All added/removed diagnostics are favorable. Some diagnostics change to
reflect top-materialized protocols explicitly.
Fixesastral-sh/ty#3443.
Co-authored-by: Charlie Marsh <charlie.r.marsh@gmail.com>
## Summary
This is a first step towards #20411. After this, we would work to either
upstream changes or adjust things within Ruff.
Performance improvements have already been upstreamed
(https://github.com/rust-lang/annotate-snippets-rs/pull/437,
https://github.com/rust-lang/annotate-snippets-rs/pull/440)
Re-implemented the following from the fork:
- Hidden snippets
(https://github.com/rust-lang/annotate-snippets-rs/issues/448)
- Renderer-level disabling of hyperlinks
- Jupyter cell indices
(https://github.com/rust-lang/annotate-snippets-rs/issues/449)
- Fixable mark
(https://github.com/rust-lang/annotate-snippets-rs/issues/450)
- `lineno_offset` (maybe not needed if #20648 is taken care of)
- anonymized lines affects origin
(https://github.com/rust-lang/annotate-snippets-rs/issues/451)
- cut indicator (maybe not needed if we can switch to unicode renderer)
Additional hacks to minimize behavior change include
- Adjust upstream's hidden severity behavior to match Ruff's
(https://github.com/rust-lang/annotate-snippets-rs/issues/452)
- How newlines are annotated
(https://github.com/rust-lang/annotate-snippets-rs/issues/454)
- To not indent for line numbers when none will be present
(https://github.com/rust-lang/annotate-snippets-rs/issues/453)
- Enabling `simd` by default
All of the above represents work that needs to be resolved to address
#20411.
`lib.name` hack is used to simplify maintenance with the assumption that
we'll continue working towards #20411.
Behavior changes that were included
- Tweak when implicit padding lines are present
- Fix Origin's line/column is now derived from the primary annotation
- Make consistent the rendering of primary/context annotations
- Fix snippets to show up for empty source (but may degrade #24528)
- Fix handling of term width
- Fix rendering of annotations between newline and first character
(granted, maybe the caller is wrong)
- Tweak multiline annotation markers
New or upcoming features annotate-snippets features that we will be able
to leverage by moving this forward
- `AnnotationKind::Visible` to improve the quality of built-in
code-folding if Ruff were to switch to it
- `DecorStyle::Unicode`
- *(upcoming)* No-graphiscs mode for screen readers (may also be useful
for AIs)
Deferred:
- Moving related `Group`s into the same `Report`
- Using `secondary_title` for any `Group` after the first in a `Report`
- Using a `Snippet`, instead of titles, for "virtual code" like
https://github.com/astral-sh/ruff/pull/27033#discussion_r3622727236
- Switching hidden snippets to `Origin`
## Test Plan
Within cpython, I ran
```console
$ hyperfine -i "../../ruff/target-baseline/release/ruff check" "../../ruff/target-update/release/ruff check" -N -m20 --output=null
Benchmark 1: ../../ruff/target-baseline/release/ruff check
Time (mean ± σ): 27.5 ms ± 1.1 ms [User: 33.0 ms, System: 108.4 ms]
Range (min … max): 25.0 ms … 31.7 ms 94 runs
Warning: Ignoring non-zero exit code.
Benchmark 2: ../../ruff/target-update/release/ruff check
Time (mean ± σ): 28.1 ms ± 2.0 ms [User: 33.4 ms, System: 105.7 ms]
Range (min … max): 24.8 ms … 38.9 ms 102 runs
Warning: Ignoring non-zero exit code.
Warning: Statistical outliers were detected. Consider re-running this benchmark on a quiet system without any interferences from other programs. It might help to use t
he '--warmup' or '--prepare' options.
Summary
../../ruff/target-baseline/release/ruff check ran
1.03 ± 0.08 times faster than ../../ruff/target-update/release/ruff check
```
Before:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/2d94dabf-b28d-48c1-b17c-52aac59fd57e"
/>
After:
<img width="486" height="583" alt="image"
src="https://github.com/user-attachments/assets/b388ada3-e3d7-4ba0-b90b-1330eb81f4be"
/>
## Summary
Stacked on #27217.
Prior to this change, we rejected assignments to fields inherited from a
frozen dataclass but allowed the equivalent deletion through an ordinary
subclass, even though it raises `FrozenInstanceError` at runtime:
```python
from dataclasses import dataclass
@dataclass(frozen=True)
class Frozen:
x: int = 1
class Child(Frozen): ...
del Child().x
```
We now synthesize frozen `__delattr__` for both frozen dataclasses and
their ordinary subclasses, reuse the frozen-method dispatch from #27217,
and continue through `super()` for non-field deletions. This preserves
descriptor and later-MRO checks, supports multiple frozen bases and
generic specializations, excludes `InitVar`, and retains the existing
Python 3.12 behavior for slotted frozen dataclasses.
The generated signatures also make direct and intermediate method
overrides consistent with frozen `__setattr__`.
## Summary
Prior to this change, we modeled a frozen dataclass's inherited
`__setattr__` as an overload that rejects known frozen fields and
returns `None` for every other attribute. That catch-all loses the
actual setter that Python calls after the frozen base.
For example, this assignment must be rejected because the next base's
setter never returns:
```python
from dataclasses import dataclass
from typing import Never
@dataclass(frozen=True)
class Frozen:
x: int = 1
class RejectsAssignment:
y: int = 1
def __setattr__(self, name: str, value: object) -> Never:
raise AttributeError(name)
class Child(Frozen, RejectsAssignment): ...
Child().y = 2
```
Previously, we accepted it. We also rejected valid assignments when a
later setter explicitly accepts a value for an otherwise read-only
property.
We now collect fields from every reachable frozen base, distinguish
frozen fields from attributes that are delegated through `super()`, and
validate delegated assignments against the actual next setter. This
preserves setter argument checking and declared attribute types, handles
both generic syntaxes, excludes `InitVar` arguments, and keeps the
existing behavior for slotted frozen dataclasses.
This is a prerequisite for #27001: it fixes the existing assignment
behavior and establishes the shared frozen-method dispatch that the
deletion change can reuse without expanding its scope.
## Summary
Prior to this change, equality and membership narrowing preserved
otherwise-incompatible union members because a subclass could override
`__eq__`. By default, we now assume that subclasses of a non-final class
do not override the inherited comparison method:
```py
class Foo: ...
def f(value: Foo | None, other: Foo) -> None:
reveal_type(None == other) # Literal[False]
if value == other:
reveal_type(value) # Foo
if value in [other]:
reveal_type(value) # Foo
```
The behavior is intentionally unsound. Users who want conservative
equality behavior can enable the single `strict-equality-narrowing`
setting, which also preserves broad builtin types instead of narrowing
them to literals:
```toml
[tool.ty.analysis]
strict-equality-narrowing = true
```
For compatibility, `strict-literal-narrowing` remains supported as an
alias for `strict-equality-narrowing`.
Closes https://github.com/astral-sh/ty/issues/3419.
## Summary
Prior to this change, we emitted `dataclass-field-order` for
`@dataclass(init=False)` even though no constructor is generated and a
custom `__init__` can validly accept the required fields.
We now skip the positional field-order check when the class-level `init`
flag is false, while preserving the existing field-level `init=False`,
keyword-only, and duplicate-`KW_ONLY` checks. The regression test covers
the original custom-constructor case.
This deliberately does not attempt to reconstruct inherited field order
when a subclass re-enables `init`; the added TODO test documents that
remaining false negative without expanding the field-inheritance model.
Closes https://github.com/astral-sh/ty/issues/3976.
## Summary
Split `ty_extensions` into a public part (`ty_extensions`), and an
internal part (`ty_extensions._internal`). For now, move everything to
`_internal`, except for:
- `static_assert`
- `Unknown`
- `AlwaysTruthy`, `AlwaysFalsy`
- `Intersection`, `Not`
- `Top`, `Bottom`
- `JustFloat`, `JustComplex`
- `NamedTupleLike`
## Summary
This PR revives #19936, which @AlexWaygood originally worked on, to add
support for `@property` protocol members.
We now represent every protocol member through four optional
capabilities:
1. The types read from a member through an instance.
2. The types written to a member through an instance.
1. The types read from a member through an implementing class.
2. The types written to a member through an implementing class.
Reads are checked covariantly, and writes are checked contravariantly.
This unifies properties with ordinary attributes while preserving the
differences between mutable instance attributes, methods, `ClassVar`,
and `Final`.
Read-only properties can be satisfied by compatible attributes or
properties. Writable properties additionally require a compatible real
write path through a property setter, custom descriptor, declared
attribute, or `__setattr__`. We share a bunch of pure attribute-write
logic with "real" assignments while keeping the consumers separate.
(It's a bit tedious, but assignments need to perform contextual
inference and emit diagnostics; protocols do not.)
A few notes following up on my live conversation with @AlexWaygood:
- A protocol `Final[T]` member is now instance-readable and
non-writable, and it can be declared without a default.
- `ClassVar[Final[T]]` additionally requires class-level readability
while remaining non-writable, and the redundant `ClassVar`/`Final`
diagnostic is suppressed for protocol bodies as it already is for
dataclasses.
- Existing terminal property-setter and `__setattr__` assignment
behavior is preserved; I did not _add_ separate semantics for arbitrary
descriptors whose `__set__` returns `Never`.
And a few notes on the boundaries of what's supported in this PR (and
what's not):
- A `ClassVar[T]` protocol member requires `T` to be readable through
both the instance and the implementing class. It cannot be written
through an instance, but a mutable `ClassVar` requires a compatible
class-level write path. `ClassVar[Final[T]]` requires both reads and
neither write.
- An instance-only attribute or property does not currently satisfy a
`ClassVar` member. (The existing conformance-related TODO for
instance-only declarations remains unresolved.)
- A callable `ClassVar` remains an attribute, not a method: both
accesses expose the same callable, whereas a method has distinct
bound-instance and unbound-class forms.
- A regular protocol method can be implemented by a compatible instance
method, `classmethod`, or `staticmethod`. This works for both subtyping
and assignability.
- Protocol members themselves declared using `@classmethod` or
`@staticmethod` remain unsupported and are represented internally using
`Todo`.
- General `type[P]` and meta-protocol behavior remains incomplete. The
class-side capabilities introduced here primarily model structural
compatibility; they do not imply complete support for ordinary access
through `type[P]`.
Closes https://github.com/astral-sh/ty/issues/1379.
Closes https://github.com/astral-sh/ty/issues/1380.
## Summary
`dataclass` raises at runtime when `order=True` is combined with
`eq=False`, or when `weakref_slot=True` is used without `slots=True`,
once the decorator is applied to a class:
```python
from dataclasses import dataclass
@dataclass(order=True, eq=False) # error: [invalid-dataclass]
class Example: ...
```
We retain statically known invalid flag combinations on the decorator
value and report the existing `invalid-dataclass` diagnostic when it is
applied, including when the decorator is stored before use:
```python
invalid = dataclass(order=True, eq=False)
@invalid # error: [invalid-dataclass]
class Example: ...
```
Non-literal boolean values remain conservative, so we only report
combinations that are definitely invalid. Unpacked decorator arguments
also continue to preserve the generated dataclass methods.
## Summary
`dataclass` accepts the same keyword options when it is called directly
with a class as when it is used as a decorator factory:
```python
from dataclasses import dataclass
class Example:
value: int
ordered = dataclass(Example, order=True)
ordered(1) < ordered(2)
```
Previously, our synthetic overloads only accepted these options when
`cls` was omitted. Valid calls such as `dataclass(Example, frozen=True)`
therefore produced `no-matching-overload`, and direct applications
always used the default dataclass parameters.
This adds the keyword-only options to the direct-call overloads and
reads dataclass arguments by parameter name, allowing the computed
parameters to be applied consistently to decorator factories, explicit
`None` calls, and direct class arguments.
## Summary
`CodeGeneratorKind::from_class` currently keys its retained Salsa query
by both the class and its specialization, even though type arguments
cannot change whether a class is dataclass-like, a `NamedTuple`, or a
`TypedDict`. Generic classes therefore retain duplicate classification
entries for each specialization.
This removes specialization from the classification query and evaluates
inherited code-generator behavior through the unspecialized MRO.
Synthesized field and member types continue to use their specialization
at the existing call sites; the added generic `dataclass_transform`
coverage verifies that `GenericModel[int]` and `GenericModel[str]`
retain distinct constructor types.
This PR implements the bulk of the logic needed for
https://github.com/astral-sh/ty/issues/2799, by building up a
`ConstraintSet` in `SpecializationBuilder`. This constraint set holds
the "pending state" of the specialization being inferred. It will
eventually _replace_ the `types` hash map, which stores a simple mapping
from typevars to inferred types, and which is always updated by unioning
together types when we find multiple solutions for a typevar.
For now, we are building up both pending state representations, and
solving from the constraint set where we can. There are two main cases
where we must fall back on the old solver:
- Any specialization that involves a `ParamSpec`
- If the constraint set returns `Unsatisfiable` or `Unconstrained`
Follow-on PRs will address these remaining cases that use the old
solver; once they are all migrated over to the constraint set solver, we
will remove the `types` field.
Closesastral-sh/ty#2572Closesastral-sh/ty#2959Closesastral-sh/ty#3037Closesastral-sh/ty#3203Closesastral-sh/ty#3228Closesastral-sh/ty#3428Closesastral-sh/ty#3483
## Summary
Prior to this change, field synthesis could accidentally follow
symbol-table order instead of class-body declaration order in
pathological cases like:
```python
from dataclasses import InitVar, dataclass
from ty_extensions import Top
@dataclass
class C:
a: Top[int]
int: InitVar[int] = 0
```
Here, `int` can be interned before its own declaration because it
already appears in `Top[int]`.
This PR carries a stable declaration ordinal through declaration lookup
and uses it when building `own_fields()`.
Closes https://github.com/astral-sh/ty/issues/3493.
## Summary
This PR adds support for class decorator return types, following Carl's
comment in
https://github.com/astral-sh/ty/issues/2604#issuecomment-3793310652:
assume unannotated decorators preserve the class binding when their
result is otherwise `Unknown`, but support explicit spelling of an
annotated decorator return type.
In more detail, the rule is roughly:
- If applying the decorator gives a non-`Unknown` result...
- And that result still retains the original class object, we preserve
the class.
- Otherwise, we replace the public binding with that result.
- If applying the decorator gives an `Unknown` result:
- We fall back to the decorator’s own shape.
- Unannotated function/method decorators are treated as
"identity-preserving", so we keep the current class binding.
- Decorators with an explicit return annotation are not, so we do _not_
preserve the binding.
As a concrete example, an unannotated decorator like the personify
example from #2604 is still treated as preserving the original class
(since we don't have a static replacement type):
```python
def personify(cls):
class Wrapped(cls):
full_name: str
def set_full_name(self, full_name: str) -> None:
self.full_name = full_name
return Wrapped
@personify
class Animal: ...
reveal_type(Animal) # <class 'Animal'>
Animal().set_full_name("John") # error: unresolved attribute
```
But if the decorator has an explicit return type, we use it for the
public class binding:
```python
class WrapBackend:
def __init__(self, cls: type[object]) -> None: ...
def get(self, key: str) -> bytes | None: ...
@WrapBackend
class CacheClient: ...
reveal_type(CacheClient) # WrapBackend
reveal_type(CacheClient.get("x")) # bytes | None
```
This gives us stable behavior for common untyped identity decorators
while leaving the advanced and unsound returned-class inference path out
of scope...
Closes https://github.com/astral-sh/ty/issues/143.
## Summary
A `frozen=True` dataclass rejects writes to all declared and undeclared
attributes; however, a non-frozen subclass of a `frozen=True` dataclass
only rejects writes to the attributes declared on the dataclass.
This PR synthesizes a set of `__setattr__` overloads for such subclasses
to narrow the scope of the "frozen" behavior to only those attributes
defined by the dataclass, matching the behavior used in Mypy and Pyright
(and at runtime).
For example, `child.y = 2` is now accepted:
```python
from dataclasses import dataclass
@dataclass(frozen=True)
class Frozen:
x: int = 1
class Child(Frozen):
y: int
child = Child()
child.x = 2 # runtime: FrozenInstanceError
child.y = 2 # runtime: OK
```
Closes https://github.com/astral-sh/ty/issues/3434.