[ty] Implicit instance attributes declared Final (#19462)

## Summary

Adds proper type inference for implicit instance attributes that are
declared with a "bare" `Final` and adds `invalid-assignment` diagnostics
for all implicit instance attributes that are declared `Final` or
`Final[…]`.

## Test Plan

New and updated MD tests.

## Ecosystem analysis

```diff
pytest (https://github.com/pytest-dev/pytest)
+ error[invalid-return-type] src/_pytest/fixtures.py:1662:24: Return type does not match returned value: expected `Scope`, found `Scope | (Unknown & ~None & ~((...) -> object) & ~str) | (((str, Config, /) -> Unknown) & ~((...) -> object) & ~str) | (Unknown & ~str)
```

The definition of the `scope` attribute is [here](

5f99385635/src/_pytest/fixtures.py (L1020-L1028)).
Looks like this is a new false positive due to missing `TypeAlias`
support that is surfaced here because we now infer a more precise type
for `FixtureDef._scope`.
This commit is contained in:
David Peter 2025-07-21 20:01:07 +02:00 committed by GitHub
parent dc66019fbc
commit b8dec79182
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 111 additions and 66 deletions

View file

@ -1421,6 +1421,13 @@ impl<'ast> Visitor<'ast> for SemanticIndexBuilder<'_, 'ast> {
self.visit_expr(&node.annotation);
if let Some(value) = &node.value {
self.visit_expr(value);
if self.is_method_of_class().is_some() {
// Record the right-hand side of the assignment as a standalone expression
// if we're inside a method. This allows type inference to infer the type
// of the value for annotated assignments like `self.CONSTANT: Final = 1`,
// where the type itself is not part of the annotation.
self.add_standalone_expression(value);
}
}
if let ast::Expr::Name(name) = &*node.target {