## Summary
Metaclasses can declare instance variables that their construction hooks
populate in every class they create. We already exposed these attributes
on the class object, but instance lookup only searched the constructed
class's ordinary MRO. As a result, custom enum classes could fail
protocol checks even though their metaclass populated the required
attributes at runtime.
Treat an annotation-only instance declaration directly on the concrete
metaclass as a contract for an attribute stored in each constructed
class namespace:
```python
class Meta(type):
generated: int
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
namespace["generated"] = 1
return super().__new__(mcls, name, bases, namespace)
class C(metaclass=Meta): ...
reveal_type(C().generated) # int
```
The new lookup preserves normal class and instance precedence, including
data descriptors, dynamic bases, and implicit special-method lookup.
Bound metaclass attributes and inferred method writes remain excluded
from this contract. The mdtests cover the motivating protocol case along
with the relevant class, instance, and descriptor interactions.
Closes https://github.com/astral-sh/ty/issues/3535.
## Summary
This replaces the AST `Name` used by `ProjectMetadata` with a private
`ProjectName` backed by `CompactString`.
Project names can come from distribution metadata or directory names and
are not necessarily Python identifiers. Keeping them in a dedicated type
makes that distinction explicit while preserving compact storage and the
existing string accessor.
## Summary
This represents parameter display names as the original `Name` plus a
small display prefix instead of constructing synthetic names such as
`*args` and `**kwargs`.
Signature formatting now writes the prefix only when rendering, and
diagnostic contexts retain an owned wrapper that clones or shares the
underlying identifier without allocating a decorated `Name`.
## Summary
Previously, rendering edits in preview mode involved taking a diff of
the entire file (for non-notebooks) for each separate violation/fix.
Instead, we now take a small context window around the edit, and diff
that instead. This gives a **1.75-3.6x** speed up on real world cases.
No AI was used in generating the code or PR text.
## Test Plan
Correctness tested with `cargo nextest run`.
Performance tested using the `profiling` profile on the python code in
the `ruff` repo:
- current `main`:
```console
$ ./ruff_main version
ruff 0.15.20+90 (40a62bc69 2026-07-06)
$ hyperfine -w 3 -i "./ruff_main check --preview --select=ALL"
Benchmark 1: ./ruff_main check --preview --select=ALL
Time (mean ± σ): 355.7 ms ± 2.0 ms [User: 559.8 ms, System: 45.0 ms]
Range (min … max): 352.2 ms … 358.4 ms 10 runs
```
- this PR:
```console
$ hyperfine -w 3 -i "target/profiling/ruff check --preview --select=ALL"
Benchmark 1: target/profiling/ruff check --preview --select=ALL
Time (mean ± σ): 205.0 ms ± 4.6 ms [User: 401.8 ms, System: 48.2 ms]
Range (min … max): 200.2 ms … 213.9 ms 14 runs
```
Taking the min time for each, this is a 1.75x speedup. I tested other
(real) projects, and this change was even faster on them.
I think this is a solution for #24548 -- although this PR is not able to
complete that extreme example within the timeout of 3 minutes, it does
manage to render about 75% of the violations. With a timeout of 10s,
current `main` gets to about `func_0_32` on my machine, whereas this PR
gets to `func_0_415`.
---------
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
## Summary
In #25955, we started to reuse our equality logic to narrow membership
tests (`in`, `not in`). This PR then defines when the right-hand side of
an `in` or `not in` test has behavior that is precise enough for us to
use that reasoning.
For nominal types, we walk the statically visible MRO. `list`, `set`,
`frozenset`, `dict`, `tuple`, and `range` use the "containment domain"
of their specialized built-in base when we reach that base before any
custom `__contains__` implementation. Final classes that only define
`__iter__` can also use their iteration domain, while open iterable
classes remain conservative because a subclass could add `__contains__`.
A visible `__contains__` override on the class or an intermediate base
disables narrowing:
```python
from typing import Literal, TypedDict
class Payload(TypedDict):
value: int
class MissingList(list[Literal["missing"]]):
pass
class ContainsEverything(list[Literal["missing"]]):
def __contains__(self, value: object) -> bool:
return True
def inherited(value: Payload | Literal["missing"], values: MissingList) -> None:
if value in values:
reveal_type(value) # Literal["missing"]
def overridden(value: Payload | Literal["missing"], values: ContainsEverything) -> None:
if value in values:
reveal_type(value) # Payload | Literal["missing"]
```
The rule is intentionally unsound for open subclasses of built-ins. At
runtime, a `list[T]` could be a subclass that overrides `__contains__`,
but we assume it isn't. This matches our existing policy for tuple
dunder methods, where we assume unsafe overrides will eventually be
reported at the definition site.
## Summary
`float`s that were embedded in unions were not recognized by our lax
mode mapping (since we were only looking for the expanded `float |
int`), so they were mapped to `Any` instead of `LaxFloat`, which lead to
overly permissive lax types.
closes https://github.com/astral-sh/ty/issues/3946
## Test Plan
Added a regression test
In the legacy solver, when a nominal instance is matched against a
(formal) `Callable`, use the `(Type::Callable(formal_callable), _)`
match arm which handles the transformation of a nominal instance into a
callable object. This allows us to solve cases like
```py
from typing import Callable
def call[R](callable: Callable[[], R]) -> R:
return callable()
class MyCallable:
def __call__(self) -> int:
return 1
my_callable = MyCallable()
reveal_type(call(my_callable)) # previously: Unknown, now: int
```
closes https://github.com/astral-sh/ty/issues/3763
The ecosystem impact here shows the downstream fallout of type inference
becoming more precise. I didn't spot anything that would indicate a
problem with this particular change.
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This adds additional Google-style section types to the ones that we
recognize in a docstring. For the moment this is inert, but it will soon
allow us to [render those additional section types as
Markdown](https://github.com/astral-sh/ruff/pull/26599).
## Test Plan
Since this new code is inert, we are relying on existing regression
coverage.
<!-- How was it tested? -->
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This is a minor refactor to remove some unnecessary duplication in
tests.
## Test Plan
See modified tests.
<!-- How was it tested? -->
This showed a massive performance win for #25559; pulling it out into a
separate PR.
We have several operations that existentially quantify away a set of
typevars. Before, we would do this one typevar at a time, producing an
intermediate BDD after each. This was causing a big performance hit on
#25559, where we are about to start deferring quantification until we
start extracting solutions from a constraint set. That means that (a) we
have a larger set of typevars to quantify at once, and (b) we've built
up a larger, more complex BDD by the time we're ready to quantify.
Quantifying the first typevar is fine, but that produces an even larger
BDD, which then feeds into quantifying the second typevar, which
produces an even larger...and so on. There _are_ opportunities for the
quantification to _simplify_ things and produce a smaller BDD, but
there's no guarantee where in the sequence of typevars that will happen.
The main contribution of this PR is to quantify all of the typevars in a
single pass through the original BDD. That change is actually pretty
straightforward. But it identified an issue (that already had a TODO
comment describing it) in our "nested subsitution" logic. That logic
tries to identify runaway expansions in a constraint whose typevar
appears recursively in its lower/upper bound. The detection logic was
too simple, and could incorrectly flag unrelated expansions as being
runaways. The new logic tracks a separate chain of expansions (called
"histories" in the code) for each assignment in the path.
## Summary
Closes#20729.
This marks `PYI061` fixes as unsafe in non-stub Python files.
The fix can rewrite `Literal["foo", "bar", None]` into `Literal["foo",
"bar"] | None`. That is equivalent for type checkers, but it is not
fully equivalent at runtime: code that introspects annotations with
`typing.get_args()` observes a different structure after the rewrite.
Stub files keep the previous behavior, since they are not runtime Python
files: fixes are still safe unless comments are removed.
I also added a regression case to the existing `PYI061.py` fixture.
While updating the snapshots, this also removes trailing whitespace from
the affected diagnostic messages.
## Test Plan
Reproduced the issue before the change:
```sh
cargo run -p ruff -- check /tmp/pyi061_repro.py --select PYI061 --fix --diff --no-cache --isolated
```
Verified that after the change, the fix is no longer applied by default
and is only available with `--unsafe-fixes`.
Verified that the fix is still available with unsafe fixes enabled:
```sh
cargo run -p ruff -- check /tmp/pyi061_repro.py --select PYI061 --fix --diff --unsafe-fixes --no-cache --isolated
```
Ran the targeted snapshot tests:
```sh
CARGO_PROFILE_DEV_OPT_LEVEL=1 INSTA_FORCE_PASS=1 INSTA_UPDATE=always CARGO_PROFILE_DEV_DEBUG="line-tables-only" MDTEST_UPDATE_SNAPSHOTS=1 cargo test -p ruff_linter rule_redundantnoneliteral_path_new_pyi061 -- --nocapture
```
Also ran:
```sh
cargo dev generate-all
uv run --only-group dev --locked prek run --files crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI061.py crates/ruff_linter/src/rules/flake8_pyi/rules/redundant_none_literal.rs crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.py.snap crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__PYI061_PYI061.pyi.snap crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.py.snap crates/ruff_linter/src/rules/flake8_pyi/snapshots/ruff_linter__rules__flake8_pyi__tests__py38_PYI061_PYI061.pyi.snap
git diff --check
```
---------
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
<!-- What's the purpose of the change? What does it do, and why? -->
This refactors how we extract parameter documentation from Google-style
docstrings. It replaces the existing regex-based scanner in
`ty_ide/src/docstring.rs` with a parser that should strictly improve
parameter documentation extraction along the following dimensions:
- We will now recognize parameters from `Keyword Args` and `Other Args`
sections (as well their other common spellings), where previously we
only recognized parameters from `Args` and `Parameters` sections.
- We now respect PEP 257 indentation and container boundaries, thereby
ignoring parameter-like text that appears inside Markdown fences/lists,
doctests, and reStructuredText directives, field lists, and literal
blocks.
- We now recognize continuation prose in parameter documentation more
consistently.
- We now extract docs for all parameters in a comma-separated list.
In addition, to those immediate improvements, this new section visitor
provides the source text range tracking that will allow us to render
Google-style docstring as markdown in an [upcoming
change](https://github.com/astral-sh/ruff/pull/26599).
Please note that I have intentionally biased this parser towards
successfully parsing shapes that were actually found in the wild during
a corpus review of popular public repositories that use Google-style
docstrings. As such, there are theoretically possible shapes that we do
not bother to support because they are very unlikely to occur in real
docstrings. I think this is an acceptable compromise in favour of
maintainability.
## Test Plan
Please see included tests.
<!-- How was it tested? -->
## Summary
Recognize frozen models that have `frozen=True` in their model config:
```py
class Person(BaseModel):
model_config = ConfigDict(frozen=True)
name: str
person = Person(name="Alice")
person.name = "Bob" # error: [invalid-assignment]
```
With this change, we can now also get rid of the
`DataclassTransformerParams` that were still stored in every Pydantic
model's metadata.
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
Updated Markdown tests
## Summary
Attach existing assignability error context when an explicit type
argument fails a TypeVar upper bound.
Closes https://github.com/astral-sh/ty/issues/3940.
For the motivating case in that issue, this now clarifies why the
concrete type is not assignable to the protocol.
## Validation
Added mdtest with inline diagnostic snapshot.
## Summary
Report the actual and required read types for incompatible protocol
attributes, distinguishing missing writable capabilities from members
that reject the required write type.
For the motivating case, the diagnostic now explains:
```text
info: type `C` is not assignable to protocol `WithValue`
info: └── protocol member `value` is incompatible
info: └── the member does not accept writes of type `str | None`
```
Related to astral-sh/ty#3940.
## Testing
Added mdtests with inline diagnostic snapshots.
## Summary
A Pydantic field which uses `...` (ellipsis) for the `default` argument
is actually required and provides no default value.
```py
class Model(BaseModel):
value: Any = Field(...)
Model() # error
```
towards https://github.com/astral-sh/ty/issues/2403
## Ecosystem
The two new diagnostics are false positives due to missing support for
`AliasChoices`. I think they are acceptable. They were missing
previously because we were modeling something completely wrong, so it's
hardly a regression (we only recently removed those diagnostics when
adding support for `extra`).
## Test Plan
Updated Markdown tests
## Summary
When a Pydantic model uses a `RootModel` as a field, that field can
either be passed as an instance of the class (`IntList`), or as the
underlying type directly (`list[int]`):
```py
class IntList(RootModel[list[int]]): ...
class Model(BaseModel):
int_list: IntList
Model(int_list=IntList([1, 2, 3])) # okay
Model(int_list=[1, 2, 3]) # also okay
Model(int_list=1) # error
```
Prior to this PR, we allowed `Any` type to be passed for `RootModel`
fields.
towards https://github.com/astral-sh/ty/issues/2403
## Ecosystem
The new diagnostic on prefect looks like a true positive.
## Test Plan
Updated Markdown tests
## Summary
Pydantic models can be configured via class keywords, via `ConfigDict`,
and also via plain dictionary literals. Here, we add support for the
third variant (the other two are already supported):
```py
class PlainDictConfig(BaseModel):
model_config = {"extra": "forbid"}
name: str
PlainDictConfig(name="Alice", something_else=7) # error: [unknown-argument]
```
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
Updated Markdown tests
## Summary
Closes https://github.com/astral-sh/ruff/issues/12912 by only applying
the tuple generator behavior of the rule on Python 3.14+, where tuple
generator expression got optimized in (ref:
https://github.com/python/cpython/pull/131737). Rendering the concerns
on that issue no longer relevant on those Python versions.
This was especially problematic for `C409` as only some behaviour is in
preview, not the rule itself, so you couldn't use
`tool.ruff.lint.explicit-preview-rules = true`
## Test Plan
New snapshot should pass on CI
---
Note: Code changed by Claude Sonnet 4.6. Reviewed by human, although I
don't know much about Rust (but this seems a simple enough change)
## Summary
Underscore-prefixed attributes are considered private and do not become
fields in Pydantic models:
```py
class Person(BaseModel):
name: str
_implicit_private: int
Person(name="Alice") # okay
```
## Test Plan
Updated tests
## Summary
`BaseSettings` fields can be supplied via environment variables. To
support this use case, we make all fields on these models optional by
default.
```py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
host: str
port: int
# Would succeed at runtime if HOST and PORT environment variables are set
Settings()
```
closes https://github.com/astral-sh/ty/issues/1070
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
Updated existing Markdown tests
## Summary
If `validation_alias` is specified, it[ takes precedence over `alias`
](https://pydantic.dev/docs/validation/latest/concepts/fields#field-aliases)
for purposes of the constructor signature, so here, we implement this by
simply overriding the `alias` attribute on the field.
## Test Plan
Update Markdown tests.
## Summary
Extend the Pydantic test suite to include a few more features that we
want to support.
## Test Plan
Tested all assertions against Pydantic's runtime behavior.
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:
- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->
## Summary
This change fixes https://github.com/astral-sh/ty/issues/3877 "Type of
`__doc__` should not be `str | None` when docstring exists"
The approach follows the same method that is already used for
`ModuleType.__file__`, which is also in
`module_type_implicit_global_symbol`.
## Test Plan
Initially-failing test included, and existing tests updated to reflect
this change.
fyi @millerdev @sharkdp
---------
Co-authored-by: David Peter <mail@david-peter.de>
## Summary
Pydantic model fields are typically set using their alias name, not
their field name (just like for dataclasses):
```py
class Person(BaseModel):
name: str = Field(alias="full_name")
Person(full_name="Alice") # okay
Person(name="Alice") # error
```
However, both of these behaviors can be controlled by setting
`validate_by_alias` and `validate_by_name`, which are `true` and `false`
by default. So for example, when both of these are inverted, we get the
opposite behavior:
```py
class Person(BaseModel):
model_config = ConfigDict(validate_by_alias=False, validate_by_name=True)
name: str = Field(alias="full_name")
Person(full_name="Alice") # error
Person(name="Alice") # okay
```
closes https://github.com/astral-sh/ty/issues/1438
towards https://github.com/astral-sh/ty/issues/2403
## Test Plan
Update Markdown tests.