[ty] Detect illegal multiple inheritance with NamedTuple (#19943)

This commit is contained in:
Alex Waygood 2025-08-18 13:03:01 +01:00 committed by GitHub
parent 5e4fa9e442
commit fbf24be8ae
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 250 additions and 76 deletions

View file

@ -115,15 +115,28 @@ class Location(NamedTuple):
### Multiple Inheritance
Multiple inheritance is not supported for `NamedTuple` classes:
<!-- snapshot-diagnostics -->
Multiple inheritance is not supported for `NamedTuple` classes except with `Generic`:
```py
from typing import NamedTuple
from typing import NamedTuple, Protocol
# This should ideally emit a diagnostic
# error: [invalid-named-tuple] "NamedTuple class `C` cannot use multiple inheritance except with `Generic[]`"
class C(NamedTuple, object):
id: int
name: str
# fmt: off
class D(
int, # error: [invalid-named-tuple]
NamedTuple
): ...
# fmt: on
# error: [invalid-named-tuple]
class E(NamedTuple, Protocol): ...
```
### Inheriting from a `NamedTuple`

View file

@ -0,0 +1,73 @@
---
source: crates/ty_test/src/lib.rs
expression: snapshot
---
---
mdtest name: named_tuple.md - `NamedTuple` - `typing.NamedTuple` - Multiple Inheritance
mdtest path: crates/ty_python_semantic/resources/mdtest/named_tuple.md
---
# Python source files
## mdtest_snippet.py
```
1 | from typing import NamedTuple, Protocol
2 |
3 | # error: [invalid-named-tuple] "NamedTuple class `C` cannot use multiple inheritance except with `Generic[]`"
4 | class C(NamedTuple, object):
5 | id: int
6 |
7 | # fmt: off
8 |
9 | class D(
10 | int, # error: [invalid-named-tuple]
11 | NamedTuple
12 | ): ...
13 |
14 | # fmt: on
15 |
16 | # error: [invalid-named-tuple]
17 | class E(NamedTuple, Protocol): ...
```
# Diagnostics
```
error[invalid-named-tuple]: NamedTuple class `C` cannot use multiple inheritance except with `Generic[]`
--> src/mdtest_snippet.py:4:21
|
3 | # error: [invalid-named-tuple] "NamedTuple class `C` cannot use multiple inheritance except with `Generic[]`"
4 | class C(NamedTuple, object):
| ^^^^^^
5 | id: int
|
info: rule `invalid-named-tuple` is enabled by default
```
```
error[invalid-named-tuple]: NamedTuple class `D` cannot use multiple inheritance except with `Generic[]`
--> src/mdtest_snippet.py:10:5
|
9 | class D(
10 | int, # error: [invalid-named-tuple]
| ^^^
11 | NamedTuple
12 | ): ...
|
info: rule `invalid-named-tuple` is enabled by default
```
```
error[invalid-named-tuple]: NamedTuple class `E` cannot use multiple inheritance except with `Generic[]`
--> src/mdtest_snippet.py:17:21
|
16 | # error: [invalid-named-tuple]
17 | class E(NamedTuple, Protocol): ...
| ^^^^^^^^
|
info: rule `invalid-named-tuple` is enabled by default
```