ruff/crates/ty_python_semantic/resources/mdtest/generics
Douglas Creager aba0bd568e
[ty] Diagnostic for generic classes that reference typevars in enclosing scope (#20822)
Generic classes are not allowed to bind or reference a typevar from an
enclosing scope:

```py
def f[T](x: T, y: T) -> None:
    class Ok[S]: ...
    # error: [invalid-generic-class]
    class Bad1[T]: ...
    # error: [invalid-generic-class]
    class Bad2(Iterable[T]): ...

class C[T]:
    class Ok1[S]: ...
    # error: [invalid-generic-class]
    class Bad1[T]: ...
    # error: [invalid-generic-class]
    class Bad2(Iterable[T]): ...
```

It does not matter if the class uses PEP 695 or legacy syntax. It does
not matter if the enclosing scope is a generic class or function. The
generic class cannot even _reference_ an enclosing typevar in its base
class list.

This PR adds diagnostics for these cases.

In addition, the PR adds better fallback behavior for generic classes
that violate this rule: any enclosing typevars are not included in the
class's generic context. (That ensures that we don't inadvertently try
to infer specializations for those typevars in places where we
shouldn't.) The `dulwich` ecosystem project has [examples of
this](d912eaaffd/dulwich/config.py (L251))
that were causing new false positives on #20677.

---------

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
2025-10-13 19:30:49 -04:00
..
legacy [ty] Diagnostic for generic classes that reference typevars in enclosing scope (#20822) 2025-10-13 19:30:49 -04:00
pep695 [ty] bidirectional type inference using function return type annotations (#20528) 2025-10-11 00:38:35 +00:00
builtins.md [ty] Support using legacy typing aliases for generic classes in type annotations (#18404) 2025-06-03 12:09:51 +01:00
scoping.md [ty] Diagnostic for generic classes that reference typevars in enclosing scope (#20822) 2025-10-13 19:30:49 -04:00