Fixed a false negative that occurs when reassigning a Final variable within a class body. This addresses #7797. (#7801)

This commit is contained in:
Eric Traut 2024-04-29 15:36:45 -07:00 committed by GitHub
parent 4c1eb615af
commit 1aed0e3261
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 20 additions and 6 deletions

View File

@ -3182,11 +3182,20 @@ export class Checker extends ParseTreeWalker {
if (decl.type === DeclarationType.Variable) {
if (decl.inferredTypeSource) {
if (sawAssignment) {
// We check for assignment of Final instance and class variables
// the type evaluator because we need to take into account whether
// the assignment is within an `__init__` method, so ignore class
// scopes here.
if (scopeType !== ScopeType.Class) {
let exemptAssignment = false;
if (scopeType === ScopeType.Class) {
// We check for assignment of Final instance and class variables
// in the type evaluator because we need to take into account whether
// the assignment is within an `__init__` method, so ignore class
// scopes here.
const classOrFunc = ParseTreeUtils.getEnclosingClassOrFunction(decl.node);
if (classOrFunc?.nodeType === ParseNodeType.Function) {
exemptAssignment = true;
}
}
if (!exemptAssignment) {
reportRedeclaration = true;
}
}

View File

@ -52,6 +52,11 @@ class Foo:
_member7: Final = 6
__member8: Final = 6
member9: Final = 2
# This should generate an error.
member9 = 3
def __init__(self, a: bool):
# This should generate an error because a Final
# member outside of a stub file or a class body

View File

@ -374,7 +374,7 @@ test('Final2', () => {
test('Final3', () => {
const analysisResults = TestUtils.typeAnalyzeSampleFiles(['final3.py']);
TestUtils.validateResults(analysisResults, 32);
TestUtils.validateResults(analysisResults, 33);
});
test('Final4', () => {