## Summary
This PR splits `mismatched-type-name` into eight independently
configurable warnings for `NewType`, functional enums, `TypeVar`,
`ParamSpec`, `TypeVarTuple`, `namedtuple`/`NamedTuple`, `TypedDict`, and
`TypeAliasType`.
~~This PR is actually quite a bit less breaking for users than other
rule splits we've done over the last few days. Because
`mismatched-type-name` is no longer the canonical name for _any_ rule on
this branch, we're able to make it a deprecated alias for _all_ the new
rules, meaning that it will continue to work on the CLI, in ty
configuration files, and ty suppression comments (we'll just emit a
warning diagnostic telling users to upgrade their configuration
file/suppression comment).~~
~~A more specific rule takes precedence over the deprecated name if both
are given within the same configuration table. On the command line, the
last matching flag wins (e.g. `--error=mismatched-enum-name
--ignore=mismatched-type-name` will suppress diagnostics for mismatched
enum names).~~
(After review from @MichaReiser, I backed out these changes. It's now a
somewhat breaking change, because the rule is now marked as "removed"
rather than "deprecated".)
As well as splitting the rule into eight separate rules, it also cleans
up our error recovery for several of these type factories. For example,
in the following snippet, we fail to recognize `T` as a `TypeVar` due to
bad error recovery from the non-literal name. But we don't really need a
nonliteral name in this case to determine that it's a validly
constructed TypeVar. It's probably a mistake, but there's no _soundness_
issue here:
```py
from typing import TypeVar
def f(x: str):
# main emits an error: `invalid-typevar`
# this PR emits a warning: `mismatched-typevar-name`
T = TypeVar(x)
def g(x: T) -> T:
return x
reveal_type(g(42)) # main: Todo. This PR: `Literal[42]`.
```
## Motivation
The main motivation here is that having a namedtuple or enum with the
"wrong name", for example, just seems much less "obviously wrong" than
having a typevar or paramspec with the "wrong name". The [ecosystem
report](https://github.com/astral-sh/ruff/pull/29957#issuecomment-6603964612)
is evidence of this. namedtuples and enums define runtime classes that
can be used in runtime contexts and instantiated; these constructs
aren't _just_ for type checkers.
TypeVars/ParamSpecs/TypeVarTuples/NewTypes/TypedDicts are all _only_ for
type checkers and there's no plausible reason why you'd want to give the
type a different name to the variable it's assigned to.
`mismatched-namedtuple-name` and `mismatched-enum-name` are therefore
now disabled by default, matching the default severity we already
settled on for `mistmatched-sentinel-name` in
https://github.com/astral-sh/ruff/pull/27206. `mismatched-typevar-name`,
`mismatched-paramspec-name`, `mismatched-typevartuple-name`,
`mismatched-enum-name`, `mismatched-namedtuple-name` and
`mismatched-newtype-name` all remain enabled by default with `warning`
severity.
## Summary
Use a shared ty override for Ruff’s standalone scripts now that PEP 723
scripts can inherit project settings. Fix the diagnostics in the two PR
automation scripts so they can use the same checks.
## Notes to reviewers
All 28 standalone scripts passed ty with locked dependencies, and the
changed-file hooks and mocked workflow checks passed.
---------
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
## 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.
Enable `require-build-hashes` for the Python projects and inline scripts
so isolated builds require declared hashes for their build dependencies.
Pin the build backends and their dependencies with hashes.
---------
Co-authored-by: zaniebot <242828183+zaniebot@users.noreply.github.com>
## Summary
Enable `truthiness-test-of-none-union` in the standalone scripts' inline
configuration and in the `py-fuzzer` and `ty_benchmark` projects,
following #28889.
## Summary
The upstream https://github.com/python/typing generated html now has a
breakdown of total test cases passing for each typechecker.
These total don't match what the `conformance.py` emits in it's summary:
https://github.com/astral-sh/ruff/pull/28001#issuecomment-5410032559
> The number of fully passing files held steady at 112/136.
versus
<img width="235" height="132" alt="image"
src="https://github.com/user-attachments/assets/6af76b8d-9002-4b00-ac87-b55afb0c15f8"
/>
This is because the summary is generated from `TestCase` which track
`ty` diagnostics, if there are no diagnostics because the relevant test
is designed to emit none they are not included in the count.
So instead we also use the full `test_files` to fill in the missing
stats.
NOTE: I have also bumped `CONFORMANCE_SUITE_COMMIT` which brings in some
recent spec related changes (not just version bumps)
## Test Plan
`CONFORMANCE_SUITE_COMMIT=cf943ccbea5596ef969eec6e2260097ff697b7ba uv
run --no-project --python 3.12 scripts/conformance.py --old-ty uvx
ty@0.0.75 --new-ty uvx ty@0.0.75 --tests-path ~/dev/typing/conformance`
```md
## [Typing conformance results](https://github.com/python/typing/blob/cf943ccbea5596ef969eec6e2260097ff697b7ba/conformance/)
### No changes detected ✅
<details>
<summary>Current numbers</summary>
<br>
The percentage of diagnostics emitted that were expected errors held steady at <b>97.79%</b>. The percentage of expected errors that received a diagnostic held steady at <b>94.41%</b>. The number of fully passing files held steady at <b>121/145</b>.
</details>
```
Python tooling can currently build third-party source distributions. Set
`no-build` in the maintained Python projects and PEP 723 scripts,
retaining named exceptions for Git-pinned tooling and the local
ecosystem runner. Pin the isolated build dependencies for those
exceptions, including their transitive requirements.
Follows merged astral-sh/ruff#27856, which gives the legacy `ruff-lsp`
suite a dedicated, locked Python 3.12 test environment.
Follow-up to astral-sh/ruff#27843. Replaces astral-sh/ruff#27840, which
closed when the merged docs branch was deleted.
Co-authored-by: zaniebot <242828183+zaniebot@users.noreply.github.com>
## Summary
Protocol instance attributes must be declared in the protocol class body
or inherited from a superclass. We previously accepted attributes
introduced only by assignments to `self` inside protocol methods, even
though those attributes are not part of the protocol interface.
This emits `ambiguous-protocol-member` for ordinary, annotated,
annotation-only, and augmented assignments to undeclared protocol
instance attributes:
```python
class Template(Protocol):
name: str
def method(self) -> None:
self.temp: list[int] = [] # warning: undeclared protocol member
```
Closes https://github.com/astral-sh/ty/issues/3758.
## Summary
Prior to this change, we could recognize exhaustive match statements
when a fixed tuple's finite combinations were written as an explicit
union, but not when those alternatives were hidden inside the tuple
element types:
```python
def f(b_1: bool, b_2: bool) -> int:
match (b_1, b_2):
case (True, True):
return 0
case (False, _):
return 1
case (_, False):
return 2
```
We now share the existing bounded type-expansion logic used during
overload resolution and use the expanded union when computing match
reachability. For `tuple[bool, bool]`, this lets each preceding case
subtract the combinations it covers until no alternatives remain.
The expanded type is used only for reachability, so subject and capture
inference remain unchanged. Tuple products remain capped at 64
alternatives; larger products keep the existing conservative behavior.
This also resolves the existing `tuple[int | str]` sequence-pattern
exhaustiveness TODO.
Closes https://github.com/astral-sh/ty/issues/3807.
## Summary
Per the spec:
> A named tuple class can be subclassed, but any fields added by the
subclass are not considered part of the named tuple type. Type checkers
should enforce that these newly-added fields do not conflict with the
named tuple fields in the base class.
The spec then provides this example:
```python
class Point(NamedTuple):
x: int
y: int
units: str = "meters"
class PointWithName(Point):
name: str # OK
x: int # Type error (invalid override of named tuple field)
```
We take a slightly more expansive view here, rejecting any attributes
(with or without an annotation, with or without a default) and
properties in a `NamedTuple` subclass. This seems to match Pyright and
Pyrefly, though Mypy doesn't flag these.
Shadowing an attribute in this way leads to odd behavior that is
probably never what you want, e.g.:
```python
from typing import NamedTuple
class A(NamedTuple):
x: int
class B(A):
x: int = 42
b = B(1)
print(b.x) # 42
print(b[0]) # 1
print(repr(b)) # B(x=1)
b.x = 99
print(b.x) # 99
print(b[0]) # 1
print(repr(b)) # B(x=1)
```
## Summary
We now use the same error code for all of these, with the same range,
and it's a warning by default:
```python
N = NamedTuple("O", [])
TD = TypedDict("TE", {})
T = TypeVar("U")
P = ParamSpec("Q")
NT = NewType("N", int)
```
It also implements more graceful recovery for `TypeVar`,
`TypeAliasType`, `ParamSpec`, and `NewType`.
Closes https://github.com/astral-sh/ty/issues/3255.
## Summary
This PR fixes the last remaining conformance failure on
`enums_members.py` in the conformance suite.
Implements a new lint rule `invalid-enum-member-annotation` that detects
type annotations on enum members. According to the typing spec, enum
members should not have explicit type annotations, as the actual runtime
type is the enum class itself, not the annotated type.
The rule:
- Flags annotated enum members (e.g., `DOG: int = 2` in an `Enum` class)
- Allows bare `Final` annotations (which don't specify a type)
- Excludes dunder names, private names, and special sunder names like
`_value_` and `_ignore_`
- Excludes pure declarations without values (non-members)
## Test Plan
mdtests
## Summary
This PR implements the following paragraph in the typing spec:
> Type checkers should infer a final attribute that is initialized in a
class body as being a class variable, except in the case of
[Dataclasses](https://typing.python.org/en/latest/spec/dataclasses.html),
where `x: Final[int] = 3` creates a dataclass field and instance-level
final attribute `x` with default value `3`; `x: ClassVar[Final[int]] =
3` is necessary to create a final class variable with value `3`. In
non-dataclasses, combining `ClassVar` and `Final` is redundant, and type
checkers may choose to warn or error on the redundancy.
>
>
https://typing.python.org/en/latest/spec/qualifiers.html#semantics-and-examples
## Test Plan
New Markdown tests
We now infer specializations that involve generic protocols. This
includes recursing into the methods of the protocol, matching up the
signatures of the class's methods with the signatures of the protocol,
and adding bindings for any typevars that appear in the protocol
signatures.
This required several performance updates, which were pulled out and
merged as separate PRs. There is still a performance and memory hit, but
I think a reasonable one, given the new functionality that this opens
up.
There are still some ecosystem false positives that relate to how this
interacts with overload resolution, but I plan to tackle that in
follow-on PRs.
---------
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Fixes https://github.com/astral-sh/ty/issues/1762. If a type assertion
fails, but the actual type is an unspellable subtype of the asserted
type, we now emit `assert-type-unspellable-subtype` rather than
`type-assertion-failure`. We also ignore this error in
`scripts/conformance.py`. This results in 17 fewer false positives on
the conformance suite, and it's also something that our users have asked
for.