Commit Graph
229 Commits
Author SHA1 Message Date
Alex Waygood d8c6e237e7 [ty] Split mismatched-type-name by type constructor (#29957)
## Summary

This PR splits `mismatched-type-name` into eight independently
configurable warnings for `NewType`, functional enums, `TypeVar`,
`ParamSpec`, `TypeVarTuple`, `namedtuple`/`NamedTuple`, `TypedDict`, and
`TypeAliasType`.

~~This PR is actually quite a bit less breaking for users than other
rule splits we've done over the last few days. Because
`mismatched-type-name` is no longer the canonical name for _any_ rule on
this branch, we're able to make it a deprecated alias for _all_ the new
rules, meaning that it will continue to work on the CLI, in ty
configuration files, and ty suppression comments (we'll just emit a
warning diagnostic telling users to upgrade their configuration
file/suppression comment).~~

~~A more specific rule takes precedence over the deprecated name if both
are given within the same configuration table. On the command line, the
last matching flag wins (e.g. `--error=mismatched-enum-name
--ignore=mismatched-type-name` will suppress diagnostics for mismatched
enum names).~~

(After review from @MichaReiser, I backed out these changes. It's now a
somewhat breaking change, because the rule is now marked as "removed"
rather than "deprecated".)

As well as splitting the rule into eight separate rules, it also cleans
up our error recovery for several of these type factories. For example,
in the following snippet, we fail to recognize `T` as a `TypeVar` due to
bad error recovery from the non-literal name. But we don't really need a
nonliteral name in this case to determine that it's a validly
constructed TypeVar. It's probably a mistake, but there's no _soundness_
issue here:

```py
from typing import TypeVar

def f(x: str):
    # main emits an error: `invalid-typevar`
    # this PR emits a warning: `mismatched-typevar-name`
    T = TypeVar(x)

    def g(x: T) -> T:
        return x
    
    reveal_type(g(42))  # main: Todo. This PR: `Literal[42]`.
```

## Motivation

The main motivation here is that having a namedtuple or enum with the
"wrong name", for example, just seems much less "obviously wrong" than
having a typevar or paramspec with the "wrong name". The [ecosystem
report](https://github.com/astral-sh/ruff/pull/29957#issuecomment-6603964612)
is evidence of this. namedtuples and enums define runtime classes that
can be used in runtime contexts and instantiated; these constructs
aren't _just_ for type checkers.
TypeVars/ParamSpecs/TypeVarTuples/NewTypes/TypedDicts are all _only_ for
type checkers and there's no plausible reason why you'd want to give the
type a different name to the variable it's assigned to.

`mismatched-namedtuple-name` and `mismatched-enum-name` are therefore
now disabled by default, matching the default severity we already
settled on for `mistmatched-sentinel-name` in
https://github.com/astral-sh/ruff/pull/27206. `mismatched-typevar-name`,
`mismatched-paramspec-name`, `mismatched-typevartuple-name`,
`mismatched-enum-name`, `mismatched-namedtuple-name` and
`mismatched-newtype-name` all remain enabled by default with `warning`
severity.
2026-11-20 12:41:39 +00:00
Micha Reiser b6d8e21241 [ty] Add project-manager.script = "uv" (#30489)
## Summary

This PR adds a new `project-manager` table:

```toml
[project-manager]
project = "uv" | "auto" | "none"
project-mode = "sync" | "metadata"
script = "uv" | "none"
```

This PR only implements the script part, but I listed all options to
outline where we want to go with this in the future.

`script = "uv"` opts in to installing PEP 723 script dependencies with
uv (to reduce the need for `TY_UV`). For now, `project-manager.script`
defaults to `"none"`, but I plan to change this to `"uv"` in the near
future. The new option follows the same configuration precedence as
other script settings:

* A script with its own `tool.ty` section uses the value from its own
table to control whether it uses uv to sync its dependencies or not.
* Scripts without a `tool.ty` section use the project level
`project-manager.script`

For now, overriding the setting based on file patterns isn't supported
(I have no strong reason against it, it's mainly to cut scope).

`TY_UV` takes precedence over any setting in the configuration (similar
to other CLI options that support environment variables).

The recommended way to check untrusted code is to set `TY_UV=off`, which
overrides `project-manager.script`.

For now, we keep supporting `experimental.useUv` for scripts, but the
in-editor `configuration.project-manager.script` takes precedence over
`experimental.useUv`.

## Why is the setting not under `environment.

For projects, setting `project-manager.project = "metadata"` also
changes how we discover the project (we prefer the workspace over the
closest ty project), and `metadata` doesn't initialize the Python
environment.

## LSP watch mode

Changing `project-manager.script` at the project level requires saving
any open script (or closing and reopening) for the sync to start. This
simplified the implementation a fair bit and seems an okay trade off.
2026-11-18 12:42:42 +01:00
Alex Waygood 45f24aea12 [ty] Split incompatible TypeIs narrowings into two new rules (#29949) 2026-11-17 22:20:52 +00:00
David Peter 1d40d153a9 [ty] Document runtime support in ty-extensions (#30497)
## Summary

The `ty-extensions` package lets Python evaluate and inspect
`Intersection[A, B]` and `Not[A]` at runtime. Update the stub docstrings
and the `experimental-syntax` documentation to point readers to the
package.
2026-11-17 14:41:58 +00:00
Alex Waygood a42b3d2779 [ty] Split invalid dataclass __post_init__ signatures into a separate rule (#30335) 2026-11-16 15:45:42 +00:00
Alex Waygood 1e1361d149 [ty] Use the constraints rule for single-constraint TypeVar calls (#30340) 2026-11-16 15:31:21 +00:00
Alex Waygood 4357fa3666 [ty] Split missing-module-member out of import-not-found (#30342) 2026-11-16 13:52:25 +00:00
Alex Waygood 489b338c26 [ty] Rename call-top-callable to call-to-function-with-unknown-signature (#30285) 2026-11-12 16:12:30 +00:00
Alex Waygood a550c912ad [ty] Rename dataclass-field-order to invalid-dataclass-field-order (#30289) 2026-11-12 12:31:18 +00:00
Alex Waygood 0507c5f66c [ty] Rename call-non-callable to not-callable (#30284) 2026-11-12 11:52:16 +00:00
Alex WaygoodandMicha Reiser 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>
2026-11-11 16:59:57 +00:00
Micha Reiser eeba58f5c2 [ty] Warn by default for a single overload (#30214)
## Summary

Today, `single-overload` defaults to severity error. I suggest we
downgrade the rule to warning. While this is most likely unintentional
and something the typing spec explicitly calls out type checker should
report. I don't think it should be an error:

* There's no runtime error, it does not lead to downstream errors (e.g.
because a value stores now a string instead of an int).
* It can be used to expose a narrower API than what the implementation
supports. TypeScript's compiler does not warn about a single-overlaod.
And the following is a valid use case in TypeScript, that should also
work in Python.

The use case is from VueJS:

```ts
// This component declares only the prop "foo".
useModel(props, "foo") // OK
useModel(props, "bar") // Type error: there is no "bar" prop
```

The `useModel` overload requires name (the second argument) to match
`Literal["foo"]`. So the second call is disallowed.


However, the `name` argument of the `useModel` implementation is
intentionally annotated as `name: string`, so that the implementation
can show a debug-only warning that the prop `bar` is disallowed, without
TypeScript raising any narrowing or dead code warnings.


This is certainly an advanced feature. But it suggests that there are
valid use cases for having a single overload, and that disqualifies it
from being a correctness rule.

Changing the severity doesn't change whether ty fails on CI, unless the
user explicitly opted in to existing with 0 when there are only warning
diagnostics.

## Test Plan

Verified the default severity in the CLI and ran the overload and typing
conformance tests.
2026-11-11 16:24:49 +01:00
Alex Waygood 8b1c6f06f3 [ty] Rename call-abstract-method to abstract-method-call (#30287)
## Summary

This rule flags calls such as `Base.method()` when `method` is an
abstract classmethod or staticmethod with a trivial body. The new name
describes what a suppression asks ty to ignore (“an abstract method
call”), so it better conforms to [Ruff’s rule naming
convention](https://docs.astral.sh/ruff/rule-proposals/#rule-naming-convention).
`ty: ignore[abstract-method-call]` now makes grammatical sense when read
as a sentence in English.

`call-abstract-method` remains a compatibility alias. Existing
configuration and suppression comments still work, and ty warns when
they use the old name.
2026-11-11 14:56:02 +00:00
Alex Waygood bf3591bb03 [ty] Rename implicit-concatenated-string-type-annotation to implicit-string-concatenation-in-annotation; improve documentation (#30286) 2026-11-11 14:08:11 +00:00
David Peter fb03e3cff8 [ty] Use "Rule history" sections consistently (#30258)
# Summary

Follow-up to [the review comment on
#30143](https://github.com/astral-sh/ruff/pull/30143#discussion_r4513626692).
Move the migration notes for the four rules that were split in 0.0.100
into "Rule history" sections.
2026-11-10 10:26:10 +01:00
Alex WaygoodandBrent Westbrook 4c51cc646d [ty] Give abstract class instantiation its own diagnostic rule (#29948)
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-11-09 17:06:58 +00:00
David PeterandAlex Waygood b8da5e8dbd [ty] Split out lost-keyword-for-regular-parameter from incompatible-method-override (#30143)
## Summary

We split out a new `lost-keyword-for-regular-parameter` rule for a
special case of `incompatible-method-override` where the overriding
method drops a keyword parameter (renames it, or makes it
positional-only). This is how the new diagnostic looks like:

```python
class Base:
    def scale(self, factor: int) -> int:
        return factor * 2


class Wrong(Base):
    def scale(self, multiplier: int) -> int:
        return multiplier * 3
```

```text
error[lost-keyword-for-regular-parameter]: Override of method `scale` disallows keyword arguments allowed by the method on the base class
 --> example.py:7:9
  |
7 |     def scale(self, multiplier: int) -> int:
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Definition is incompatible with `Base.scale`
  |
 ::: example.py:2:9
  |
2 |     def scale(self, factor: int) -> int:
  |         ------------------------------- `Base.scale` defined here
info: the parameter named `multiplier` does not match `factor` (and can be used as a keyword parameter)
info: This violates the Liskov Substitution Principle

Found 1 diagnostic
```

## Test strategy

New Markdown tests

<details>
<summary>Ecosystem impact</summary>

Across 165 projects, 1,946 existing errors moved from
`incompatible-method-override` to the new rule at the same locations and
severity. The linked run used the previous name,
`missing-keyword-in-override`.

The split surfaced 65 previously suppressed errors. Sphinx (28), Kornia
(25), and Altair (2) disable the old rule in configuration. The other 10
errors appeared at inline suppressions in pip, Streamlit, scipy-stubs,
and pandas-stubs. Seven of those comments also triggered
`unused-ignore-comment`.

The run reported no timeouts or abnormal exits and an average timing
factor of 1.00×.

</details>

---------

Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
2026-11-09 15:24:29 +00:00
17db55b996 [ty] Separate missing and inconsistent overload implementation diagnostics (#29953)
Co-authored-by: Micha Reiser <micha@reiser.io>
Co-authored-by: David Peter <sharkdp@users.noreply.github.com>
2026-11-09 14:13:51 +01:00
David PeterandAlex Waygood 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>
2026-11-09 12:14:13 +01:00
Alex WaygoodandBrent Westbrook 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>
2026-11-06 14:46:50 -05:00
Alex WaygoodandDavid Peter d65c056994 [ty] Split invalid-key into three TypedDict diagnostic rules (#29955)
## Summary

Given a `Movie` TypedDict with a `title` field, ty currently reports
`invalid-key` for three cases. This PR gives each its own rule.

| Example | Rule |
| --- | --- |
| `movie["titel"]` reads a misspelled key | `invalid-typed-dict-key` |
| `movie[key]` reads a key whose type is `str` and whose value is
unknown | `non-literal-typed-dict-key` |
| `Movie(title="Alien", titel="Alien")` supplies an unknown key during
construction | `unknown-typed-dict-constructor-key` |

Both subscript rules apply to reads and assignments. An invalid
non-string key such as `movie[0]` reports `invalid-typed-dict-key`. The
constructor rule reports the extra `titel` key in `movie: Movie =
{"title": "Alien", "titel": "Alien"}`. For a closed TypedDict, it flags
`{key: value}` when `key` has type `str` and might introduce an extra
item.

Projects migrating to ty lose typo detection if they disable
`invalid-key` to allow dynamic TypedDict lookups. In mypy, disabling
`literal-required` allows `movie[key]` while `movie["titel"]` still
produces a `typeddict-item` error. Pyright allows the dynamic lookup by
default and also flags the typo. To keep that behavior in ty, set
`non-literal-typed-dict-key` to `ignore` and leave
`invalid-typed-dict-key` enabled.

All three rules default to `error`. With the alias handling from #29960,
`invalid-key` maps to `invalid-typed-dict-key` in configuration, inline
ignores, and existing baselines. Previously baselined diagnostics can
therefore reappear under either of the other two rule names. To preserve
a custom severity across the split, set all three rules to the same
level. For inline ignores, use the rule or rules reported on that line.

---------

Co-authored-by: David Peter <mail@david-peter.de>
2026-11-06 15:34:17 +00:00
Alex Waygood c86652abce [ty] Skip active Conda and Pixi environments during discovery if the environment doesn't contain Python (#30066) 2026-11-05 15:58:48 +00:00
Micha ReiserandDavid Peter 3c7973bd17 [ty] Warn about renamed rules in ignore comments (#30026)
## Summary

Add a new lint rule that warns about renamed rule names in ignore
comments, including a fix to apply the rename.

This is the same as ruff's
https://docs.astral.sh/ruff/rules/redirected-noqa/

---------

Co-authored-by: David Peter <sharkdp@users.noreply.github.com>
2026-11-04 17:07:53 +00:00
Micha Reiser 27452ba5b0 [ty] Don't fail configuration deserialization on conflicting rule names (#30023)
## Summary

A configuration that sets different levels for the rule and its alias
(e.g. `unresolved-import` and `import-not-found`) currently fails to
deserialize. This PR removes the validation from the configuration
deserialization path because failing during deserialization:

* Means the LSP has to fallback to the default configuration, loosing
all other user configuration. This is certainly not what users wan.t
* ty stops config discovery if it finds an invalid `pyproject.toml`,
even if there's a higher precedence `ty.toml` (ty fails on a
configuration that it isn't even using)
* serde errors don't have the same nice code frames. E.g. the old
implementation underlined the entire rules table.


Instead, we should validate the settings when converting from options to
settings. This ensures:

* That we can recover in the LSP case
* It gives us nice code frames that point to the name in the rules
table.

However, I decided to remove the error altogether in favor of my stacked
PR that adds a warning when using a deprecated rule name. The reasoning
here is:

* I don't think we should show two warnings at the same location. 
* This aligns with how we handle misspelled rule names, which is also a
warning only (and is/was a long requested change on the ruff repository)
* It matches ruff's behavior
* I don't see much harm in running ty, especially because it also gives
much better recovery in the LSP.
* ty resolves overrides lazily when resolving the settings for a
specific files. At that point, it's too late to error if the main config
and the override use both the new and alias rule name
* There are cases where options appear as if they're from a single file
when they're not. E.g., VS Code merges user-level and workspace-level
configurations. For example,
  user-settings:
  ```json
  {
    "ty.configuration": {
      "rules": { "unresolved-import": "ignore" }
    }
  }
  ```
  workspace-settings:
  ```json
  {
    "ty.configuration": {
      "rules": { "import-not-found": "warn" },
      "environment": { "extra-paths": ["./stubs"] }
    }
  }
  ```
  are merged to:
  ```json
  {
    "rules": {
      "unresolved-import": "ignore",
      "import-not-found": "warn"
    },
    "environment": {
      "extra-paths": ["./stubs"]
    }
  }
  ```
It's now hard to make an argument what the user intention was, and
failing in this case seems overly strict to me.


The path taken in this PR is to, instead, give higher precedence to the
new rule name.
## Test Plan

Added CLI and editor regression coverage and ran the CLI, project, and
editor configuration tests.
2026-11-04 16:36:21 +00:00
Micha Reiser e501689d12 [ty] Inherit project settings and overrides for PEP 723 scripts (#29793)
## Summary

This changes how ty handles script options. Up to now, scripts never
inherited any settings from the project. I think this is overly
pedantic. While I consider script isolation important in terms of
dependencies, I don't think the same is true for type checking or linter
settings. The main motivation for not-inheriting project settings is
that scripts can be shared. Checking them in isolation ensures that
everyone gets a consistent experience. I don't think this is something
most users care about in terms of linting and type checking scripts. Our
own scripts are a good example. We have multiple scripts and we have no
intention to share them outside this project. In fact, we've found it
very annoying to repeat the same ty configuration in every script.

I also ran an experiment in https://github.com/astral-sh/ruff/pull/29768
to understand the ecosystem impact of using ty's current configuration
inheritance in Ruff. Without project inheritance, 17 of 38 scripts in
the seven projects sampled had diagnostics. Not only would this be a
very disruptive change. I also think that it's very reasonable that you
want to enforce the same standard to both regular python files as well
as scripts.

This PR changes how ty resolve script settings to:

* If a script has a `tool.ty` section, ignore the project's
configuration. Users who prefer the current behavior can restore it by
adding an empty `tool.ty` section to their script (or check their script
outside the project).
* If a script has no `tool.ty` section, inherit the project's
configuration. This is the main change.
* If a script has no `tool.ty` section, and the script matches an
`overrides` entry, inherit the project and override settings, like we do
for any other file. This allows users to extend the project
configuration (except for `environment` settings).

An explicit `--config-file` still overrides any settings specified in
the script. Matching file overrides from that config also apply.

A script's `requires-python` takes precedence over the project's Python
version. An inline `environment.python-version` takes precedence over
`requires-python`.


Fixes astral-sh/ty#4083 and addresses the [ignored file override
reported in
ty#4566](https://github.com/astral-sh/ty/issues/4566#issuecomment-5762949445).


## Considerations

The main downside of this change is that changing a script's
`environment.root` from `[]` to `["."]` implies opting out of the
project's config inheritance, because it requires adding a `tool.ty`
section. I don't have a good solution to this, other that we could
consider adding a `extend` configuration option in the future, that
allows explicitly inheriting from another configuration. Which is
something users have asked for before (for projects).


The other nuanced decision in this PR is that script's inherit a
project's `environment.extra-paths`. I think this is okay, given that
the main use case is to override e.g. typing stubs. But I could see an
argument that a script should not inherit any of the search path related
settings.

## Test Plan

All script CLI tests passed, including the uv integration tests.
2026-11-04 16:36:21 +00:00
David Peter fddb68af74 [ty] Update import-not-found docs to v0.0.97 (#30020) 2026-11-04 09:12:46 +01:00
Alex Waygood 0471c14d1f [ty] Rename unresolved-import to import-not-found (#29960)
## Summary

ty currently reports `unresolved-import` for both a missing module and a
missing member in a `from` import. But the word "unresolved" is heavily
overloaded in Python, and has been reported by users as being confusing
(see https://github.com/astral-sh/ty/issues/2471). This PR renames the
rule to `import-not-found`, which describes the lookup failure in either
case.

Configuration, command-line flags, and ignore comments accept either
spelling. If several flags set this rule’s severity using different
spellings, the last flag wins. Existing baseline entries still match,
and rewriting a baseline uses the new name. Links to the old rule
heading still work.
2026-11-03 19:53:26 +00:00
Micha Reiser 207ec3affe [ty] Add diagnostic baseline support (#27636) 2026-10-26 13:34:01 -07:00
Brent Westbrook 8334c5c57d [ty] Add support for SARIF output (#29635)
Summary
--

This PR fixes astral-sh/ty#2484 by moving our SARIF rendering from
`ruff_linter` into `ruff_db` and
wiring that up as an output format for ty.

The first commit introduces the metadata and makes some other
preparatory changes to the SARIF
emitter in Ruff. The second commit then moves the emitter to `ruff_db`
and removes the remaining
Ruff-specific calls. The third commit then wires that up to ty's CLI.

Test Plan
--

Existing tests, adapted to `ruff_db`, as well as a new ty CLI test
2026-10-23 14:57:03 -04:00
David Peter 068e06a3c9 [ty] Add return-type-inference configuration (#29323)
## Summary

Introduce a new configuration option `analysis.return-type-inference`
which can be used to control the return type inference feature, which
we'll introduce in #29253. I will not merge this PR without the one on
top, but it seemed like a good idea to split it out for easy review.
2026-10-15 21:13:58 +02:00
Carl Meyer b24be84212 [ty] Add opt-in diagnostic for mismatched sentinel names (#27206)
Add an opt-in `mismatched-sentinel-name` diagnostic for
`builtins.sentinel` and `typing_extensions.Sentinel` definitions whose
name argument does not match their assignment target. The rule is
ignored by default because matching names are optional; enable it with
`--warn mismatched-sentinel-name` or the corresponding rule
configuration.

Accept unqualified names and names qualified by the full enclosing class
path, including nested classes. Constructor aliases and explicit `repr`
arguments are supported.

Fixes astral-sh/ty#4091.

## Test plan

Manually checked a sentinel with a 4,097-character literal name used as
a type annotation. Default settings accepted the annotation without
diagnostics; enabling `mismatched-sentinel-name` reported only the
naming mismatch.
2026-10-13 11:32:08 -07:00
Charlie Marsh dd619474e0 [ty] Enable invalid-mutable-override by default (#29335)
## Summary

Enable `invalid-mutable-override` as an error by default. We now reject
overrides that narrow a writable attribute's type without requiring
users to opt in:

```python
class Base:
    value: int

class Child(Base):
    value: bool  # invalid-mutable-override
```

Code accepting a `Base` can assign any `int` to `value`, violating the
subclass's `bool` annotation. The rule remains independently
configurable, so users can disable it while migrating.

Addresses [the default-severity discussion in
#28556](https://github.com/astral-sh/ruff/pull/28556#discussion_r4261238726).
2026-10-13 13:22:02 -04:00
David Peter e03746cbf4 [ty] Prepare mdtests for return type inference (#29295)
## Summary

This PR prepares our mdtests for return type inference. For example, we
had some definitions like
```py
def flag(): ...
```
which were supposed to be used in `if flag()` tests of ambiguous
truthiness. However, with return type inference, ty would understand
that this function returns `None`, which is falsy.

I'm pulling this out so as to reduce the diff on the upcoming return
type inference PR.

## Test Plan

Tested by running the return type inference implementation against these
changes.
2026-10-12 15:15:57 +02:00
Charlie Marsh 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.
2026-10-08 11:19:53 -04:00
David Peter 55129c13c4 [ty] Correct unused ignore rule documentation (#29040)
`unused-ignore-comment` reports unused `ty: ignore` directives, so its
documentation should not describe the setting that disables unused
`type: ignore` diagnostics.

Remove that incorrect option from the rule documentation and fix the
wording for `unused-type-ignore-comment`. Regenerate the rule reference
and schema.
2026-10-02 08:50:42 +02:00
David Peter 2d253467b5 [ty] Improve unresolved-import documentation (#29039)
## Summary

This is probably the first diagnostic that many new ty users will see,
to let's try to improve the docs here a bit.
2026-10-01 12:32:09 +00:00
David Peter f183d34dca [ty] Add opt-in truthiness-test-of-none-union rule (#28889)
## Summary

Add a new opt-in `truthiness-test-of-none-union ` rule which flags
truthiness checks on types like `int | None` or `str | None`. For
example, it will emit an error on the following (problematic) `if not
limit` check:

```py
def take(items: list[str], limit: int | None = None) -> list[str]:
    if not limit:  # error: [truthiness-test-of-none-union]
        return items
    return items[:limit]
```

Related to https://github.com/astral-sh/ruff/discussions/8757 and
inspired by Pyrefly's `implicit-bool` rule (but narrower in scope).

## Test strategy

New test suite
2026-09-25 22:06:20 +02:00
David Peter df0b49b8e7 [ty] Disable invalid-legacy-positional-parameter by default (#28834)
## Summary

Disable `invalid-legacy-positional-parameter` by default. Modern code
can use double-underscore-prefixed parameter names to avoid collisions
with `**kwargs`, without intending to use the legacy positional-only
convention.

The mdtest harness continues to enable the rule globally, and the
conformance runner already enables it with
`--error=invalid-legacy-positional-parameter`. Update the rule
documentation to explain the default, and regenerate the docs and
schema.

Follow-up to
https://github.com/astral-sh/ruff/pull/25079#issuecomment-5797494065.
2026-09-23 16:10:57 +00:00
Alex Waygood 68073852bf [ty] Add rules that detect suspicious uses of Callable, Iterable, Iterator or Generator types in a boolean context (#28554) 2026-09-21 17:42:00 +01:00
Charlie Marsh 1244656343 [ty] Preserve PEP 695 bindings across nested classes (#28723)
## Summary

We now preserve the enclosing class's binding when PEP 695 type
parameters are referenced in a nested class, instead of rebinding them
to the nested class's methods:

```python
class Outer[T]:
    class Inner:
        def method(self, value: T) -> T:
            return value

# def method(self, value: T@Outer) -> T@Outer
reveal_type(Outer.Inner.method)
```

The class-scope visibility restriction now applies only to legacy
bindings. This also preserves PEP 695 `ParamSpec` and `TypeVarTuple`
bindings across nested classes and intervening methods.

Closes https://github.com/astral-sh/ty/issues/4559.
2026-09-20 07:48:23 -04:00
Charlie Marsh 1dcb398a94 [ty] Diagnose unguarded cycles in implicit and PEP 613 aliases (#28704)
## Summary

We now report `cyclic-type-alias-definition` for implicit and PEP 613
aliases that refer to themselves directly or through unions, including
mutually recursive and generic aliases.

```python
from typing import TypeAlias, Union

IntOr = Union[int, "IntOr"]  # cyclic-type-alias-definition
x: IntOr

Explicit: TypeAlias = Union[int, "Explicit"]  # cyclic-type-alias-definition
y: Explicit
```

The shared alias-inference query reports errors at the alias definitions
and preserves cycle errors in a `Result` alongside the recovery type.
Both syntaxes use the same recovery path. Recursion through a containing
type remains valid.

This moves
[`aliases_recursive.py`](https://github.com/python/typing/blob/3a4ada0a0e6b380c6d7561b8392c6b159f5f374e/conformance/tests/aliases_recursive.py)
from Partial to Pass.
2026-09-19 23:42:20 -04:00
Charlie Marsh 58868211d8 [ty] Reject class-scoped type variables in __init__ receivers (#28706)
## Summary

We add `invalid-init-type-variable`, enabled as an error by default, to
enforce the [typing specification's
restriction](https://typing.python.org/en/latest/spec/constructors.html#init-method)
on class-scoped type variables in explicit `__init__` receiver
annotations:

```python
class Swapped[T, U]:
    # invalid-init-type-variable
    def __init__(self: "Swapped[U, T]") -> None: ...
```

Function-scoped type variables remain valid, and constructor inference
is unchanged. Mypy doesn't catch this, but Pyright and Pyrefly do.
2026-09-18 19:43:29 -04:00
Charlie Marsh 59806988c6 [ty] Improve diagnostics for async generator stubs (#28692)
## Summary

An `async def` stub without `yield` describes a coroutine function, even
when its return annotation is `AsyncIterator` or `AsyncGenerator`. For
example:

`stubs.pyi`:

```python
from collections.abc import AsyncIterator

async def values() -> AsyncIterator[int]: ...
```

`main.py`:

```python
from stubs import values

async def consume() -> None:
    async for value in values():
        pass
```

Before, the diagnostic identifies the missing iteration method but gives
no guidance on correcting the stub:

```text
error[not-iterable]: Object of type `CoroutineType[Any, Any, AsyncIterator[int]]` is not async-iterable
info: It has no `__aiter__` method
```

After, we point to the declaration and suggest how to declare an async
generator. We also suggest `await`, since a coroutine can intentionally
return an async iterator:

```text
error[not-iterable]: Object of type `CoroutineType[Any, Any, AsyncIterator[int]]` is not async-iterable
 --> main.py:4:24
  |
4 |     async for value in values():
  |                        ^^^^^^^^
  |
 ::: stubs.pyi:3:1
  |
3 | async def values() -> AsyncIterator[int]: ...
  | ---------------------------------------- Without `yield` in the function body this function returns a coroutine
info: It has no `__aiter__` method
help: `await` the coroutine before iterating over its result
help: To declare `values` as an async generator, use `def` rather than `async def` or add `yield` to the body
```

For declarations in dependencies, we suggest reporting an incorrect stub
to the library maintainers. The stub guidance also appears for
incompatible callable return types, including method overrides, and is
limited to functions with stub-like bodies. The typing rules are
unchanged.

Closes https://github.com/astral-sh/ty/issues/2875.
2026-09-18 18:43:00 +00:00
Micha Reiser af73c077aa [ty] Only skip uv workspace metadata for a single script (#28581) 2026-09-17 19:09:35 +02:00
Micha Reiser 0c40f14f9f [ty] Support dependency lints with --config-file (#28573) 2026-09-17 16:45:23 +02:00
Charlie MarshandAlex Waygood 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>
2026-09-15 09:20:41 -04:00
David Peter feecd77879 [ty] Document runtime limitations of experimental syntax (#28606)
## Summary

Explain that experimental type syntax can cause runtime errors in
libraries that inspect annotations.

Address [Alex's
suggestion](https://github.com/astral-sh/ruff/pull/28513#issuecomment-5678791867).
2026-09-15 11:56:49 +00:00
David Peter efb30c1f4c [ty] Align TypeIs and isinstance narrowing (#28193)
## Summary

This PR aligns `TypeIs` and `isinstance` narrowing for unspecialized
generics and gradual protocols in both strict and non-strict narrowing
modes:
- if `analysis.strict-generic-narrowing = true`, we now intersect with
the top materialization of the generic/gradual type, i.e. for a type
guard returning `TypeIs[list]`, we now narrow with the (typically
unspellable) `Top[list[Unknown]]`. Previously, we did not do this
consistently for `isinstance` narrowing either when narrowing to a
gradual protocol.
- if `analysis.strict-generic-narrowing = false` (default), we now use
the same "union filtering" approach that we also use for `isinstance`
narrowing (note that the [`TypeIs`
PEP](https://peps.python.org/pep-0742/) specifies the narrowing behavior
in terms of intersections, but allows "practical approximations of these
types"). Using the union filtering approach allows us to avoid overly
permissive gradual unions that would result from plain intersections
with a type like `list[Unknown]`. We also extend the union filtering
approach here to properly handle gradual protocols.

In both modes, the negative branch still uses the top materialization to
exclude all specializations.

The new behavior can be summarized like this:

```py
class Invariant[T]:
    value: T

def is_invariant(x: object) -> TypeIs[Invariant]: ...

@final
class Unrelated: ...
```

<table>
  <thead>
    <tr>
<th colspan="3"><code>is_invariant(x)</code> / <code>isinstance(x,
Invariant)</code></th>
    </tr>
    <tr>
      <th>Before narrowing</th>
      <th>Non-strict narrowing</th>
      <th>Strict narrowing</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>object</code></td>
      <td><code>Invariant[Unknown]</code></td>
      <td><code>Top[Invariant[Unknown]]</code></td>
    </tr>
    <tr>
      <td><code>Invariant[int] | Unrelated</code></td>
      <td><code>Invariant[int]</code></td>
      <td><code>Invariant[int]</code></td>
    </tr>
  </tbody>
</table>

```py
@runtime_checkable
class Reader(Protocol):
    def read(self) -> Any: ...

class SpecificReader:
    def read(self) -> str: ...

def is_reader(arg: object) -> TypeIs[Reader]: ...
```

<table>
  <thead>
    <tr>
<th colspan="3"><code>is_reader(x)</code> / <code>isinstance(x,
Reader)</code></th>
    </tr>
    <tr>
      <th>Before narrowing</th>
      <th>Non-strict narrowing</th>
      <th>Strict narrowing</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>object</code></td>
      <td><code>Reader</code></td>
      <td><code>Top[Reader]</code></td>
    </tr>
    <tr>
      <td><code>SpecificReader | Unrelated</code></td>
      <td><code>SpecificReader</code></td>
      <td><code>SpecificReader</code></td>
    </tr>
  </tbody>
</table>

closes https://github.com/astral-sh/ty/issues/4394 (Fixed in both
non-strict and strict mode; Before: reveals `(list[Unknown] &
~list[Unknown]) | int` and reports `invalid-return-type`, After: reveals
`int`; no errors)

## Ecosystem impact

Looks great. Lots of removed diagnostics in non-strict-mode projects,
and only very few new diagnostics in strict-mode projects, all of which
are expected with these changes here.

## Test strategy

New and updated Markdown tests
2026-09-07 15:58:57 +02:00
Alex Waygood 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>

![Uncalled
function](https://github.com/user-attachments/assets/9538e4a9-b716-4fff-a4c7-24fc6deb7994)

</details>

<details>
<summary>Uncalled method</summary>

![Uncalled
method](https://github.com/user-attachments/assets/3c327ada-eec0-4bcc-9588-e5df50b3455b)

</details>

<details>
<summary>Generator: suggest <code>any()</code></summary>

![Generator: suggest
any()](https://github.com/user-attachments/assets/83d500fb-d69a-4753-94d6-4008379af8d8)

</details>

<details>
<summary>Tuple with a fixed length</summary>

![Tuple with a fixed
length](https://github.com/user-attachments/assets/e37ade52-22a6-4946-aa29-71f5328bfa79)

</details>

<details>
<summary>Tuple with a minimum length</summary>

![Tuple with a minimum
length](https://github.com/user-attachments/assets/6fc71bd5-6a52-417f-9a9b-db4e760752c3)

</details>

<details>
<summary>Empty tuple</summary>

![Empty
tuple](https://github.com/user-attachments/assets/6c8e8242-fd8b-410d-b56b-e6a49737ea0f)

</details>

<details>
<summary>Nonempty string literals</summary>

![Nonempty string
literals](https://github.com/user-attachments/assets/139f9f53-5128-4d85-8901-01937f312986)

</details>

<details>
<summary>Empty string</summary>

![Empty
string](https://github.com/user-attachments/assets/261fc16d-dc67-44b8-bf51-58f2fcb12e2f)

</details>

<details>
<summary><code>None</code></summary>


![None](https://github.com/user-attachments/assets/c04b0308-b294-4125-bba8-3603fd5bda02)

</details>

<details>
<summary><code>TypedDict</code>: required fields and their
declarations</summary>

![TypedDict: required fields and their
declarations](https://github.com/user-attachments/assets/46367c59-665f-4b40-893b-227add4ca3df)

</details>

<details>
<summary>Final class without <code>__bool__</code> or
<code>__len__</code></summary>

![Final class without __bool__ or
__len__](https://github.com/user-attachments/assets/4e8e92e7-0645-485c-ab30-4d0807943005)

</details>

<details>
<summary>Enum: implicit finality</summary>

![Enum: implicit
finality](https://github.com/user-attachments/assets/6596a69b-a122-40bb-80fc-b011c054e15d)

</details>

### Strict-rule diagnostics

These examples enable `redundant-condition-strict` explicitly.

<details>
<summary>Indexing <code>bytes</code> returns <code>int</code></summary>

![Indexing bytes returns
int](https://github.com/user-attachments/assets/e6f33bc9-c998-4be5-b1ca-36c32b073d99)

</details>

<details>
<summary>Comparing <code>str</code> with <code>bytes</code></summary>

![Comparing str with
bytes](https://github.com/user-attachments/assets/48e15215-d6ae-4779-ab44-244c21dabf55)

</details>

<details>
<summary>Length comparison: explain the fixed tuple length</summary>

![Length comparison: explain the fixed tuple
length](https://github.com/user-attachments/assets/556ef251-ac2f-4048-b7f4-b545a8b87a69)

</details>

<details>
<summary>Comparison: omit an obvious literal's type annotation</summary>

![Comparison: omit an obvious literal's type
annotation](https://github.com/user-attachments/assets/95a0e73f-38f5-457b-9726-8169016b991d)

</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.
2026-09-05 20:45:59 +01:00
Alex Waygood 7de38e7e2a [ty] Add a new disjoint-cast rule (#28129)
## Summary

`typing.cast()` leaves its argument unchanged at runtime, but accepts
casts even when the inferred source type and destination type cannot
overlap. Add a disabled-by-default `disjoint-cast` rule to flag these
cases:

```python
from typing import cast


def f(value: int) -> str:
    return cast(str, value)  # disjoint-cast
```

Casts between overlapping types remain accepted. The rule exempts stub
files and casts to or from `Never`.

The documentation explains less obvious disjoint casts involving
invariant containers and `NewType`, and discusses `TypeGuard` as a
possible alternative. Enable the rule in ecosystem analysis to assess
its impact.

## Error-tree diagnostics

Add error-tree explanations for disjointness checks involving invariant
generic arguments, unions, tuples, protocol members, final classes, and
TypedDict fields. Secondary annotations identify the inferred source
type, the destination, and available type definitions, including
`@final` decorators.

For example, casting a class whose `values()` method returns `list[str]`
to a protocol requiring `list[int]` produces:

```text
info: protocol member `values` is incompatible
info: └── return types `list[int]` and `list[str]` are disjoint
info:     └── `int` and `str` are not mutual subtypes of each other
```

## Parallels in other type checkers

| Checker | Rule | Comparison with `disjoint-cast` |
|---|---|---|
| **basedpyright** |
[`reportInvalidCast`](https://docs.basedpyright.com/latest/benefits-over-pyright/new-diagnostic-rules/#reportinvalidcast)
| Same high-level purpose: reject casts between non-overlapping types.
Its docs explicitly demonstrate `int` → `str`, and discuss rejecting
`dict` → `TypedDict` casts. |
| **Pyrefly** |
[`invalid-cast`](https://pyrefly.org/en/docs/error-kinds/#invalid-cast)
| Disabled by default, but deliberately narrower than `disjoint-cast`:
checks disjoint **runtime classes**. It accepts `list[int]` →
`list[str]`, ignores tuple-element differences, treats TypedDicts as
overlapping with `dict`, and excludes protocols. |

Mypy and upstream Pyright do not have direct equivalents. Both can
report redundant casts, but their current `cast` implementations do not
check source/destination overlap: [mypy
implementation](https://github.com/python/mypy/blob/master/mypy/checkexpr.py#L4546),
[Pyright
implementation](https://github.com/microsoft/pyright/blob/main/packages/pyright-internal/src/analyzer/typeEvaluator.ts#L10917).

### TypeScript

TypeScript has a similar restriction on type assertions: **TS2352**
rejects assertions between types that do not sufficiently overlap. For
example:

```typescript
const value = "hello" as number; // TS2352
```

Like `typing.cast()`, TypeScript's type assertions do not perform
runtime validation. An explicit two-step assertion through `unknown` or
`any`, such as `value as unknown as Target`, can bypass the restriction.
The overlap criterion differs from ty's disjointness relation, so this
is a precedent for checking suspicious casts rather than an exact
semantic equivalent. See the [TypeScript handbook on type
assertions](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions).
2026-09-01 21:06:04 +00:00