Files
ruff/crates/ty_python_semantic/resources/lint_docs/invalid-named-tuple.md
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

2.3 KiB

What it does

Checks for invalid definitions of typing.NamedTuple and collections.namedtuple classes.

Why is this bad?

An invalidly defined NamedTuple class may lead to the type checker drawing incorrect conclusions. It may also lead to errors at runtime, such as ValueError, TypeError, or AttributeError.

Examples

A class definition cannot combine NamedTuple with other base classes in multiple inheritance; doing so raises a TypeError at runtime. The sole exception to this rule is Generic[], which can be used alongside NamedTuple in a class's bases list.

>>> from typing import NamedTuple
>>> class Foo(NamedTuple, object): ...
TypeError: can only inherit from a NamedTuple type and Generic

Further, NamedTuple field names cannot start with an underscore:

>>> from typing import NamedTuple
>>> class Foo(NamedTuple):
...     _bar: int
ValueError: Field names cannot start with an underscore: '_bar'

Nor can they be keywords:

>>> from collections import namedtuple
>>> X = namedtuple("X", ["class"])
ValueError: Type names and field names cannot be a keyword: 'class'

or invalid identifiers:

>>> from collections import namedtuple
>>> X = namedtuple("X", ["-"])
ValueError: Type names and field names must be valid identifiers: '-

Similar restrictions apply to the typename argument:

>>> from typing import NamedTuple
>>> X = NamedTuple("class", [])
ValueError: Type names and field names cannot be a keyword: 'class'
>>> X = NamedTuple("x-", [])
ValueError: Type names and field names must be valid identifiers: 'x-'

NamedTuple classes also have certain synthesized attributes (like _asdict, _make, _replace, etc.) that cannot be overwritten. Attempting to assign to these attributes without a type annotation will raise an AttributeError at runtime.

>>> from typing import NamedTuple
>>> class Foo(NamedTuple):
...     x: int
...     _asdict = 42
AttributeError: Cannot overwrite NamedTuple attribute _asdict

Finally, NamedTuple field annotations cannot use the ClassVar or Final type qualifiers. These qualifiers also cause a runtime error when annotations are evaluated eagerly:

>>> from typing import ClassVar, NamedTuple
>>> class Foo(NamedTuple):
...     x: ClassVar[int]
TypeError: typing.ClassVar[int] is not valid as type argument