Changed reportUnusedVariable diagnostic check to exempt variables whose names begin with an underscore.

This commit is contained in:
Eric Traut 2021-11-24 16:04:57 -08:00
parent 3e8101bcd0
commit ced19cbcbd
3 changed files with 39 additions and 0 deletions

View File

@ -2335,6 +2335,12 @@ export class Checker extends ParseTreeWalker {
if (decl.node.nodeType === ParseNodeType.Name) {
nameNode = decl.node;
// Don't emit a diagnostic if the name starts with an underscore.
// This indicates that the variable is unused.
if (nameNode.value.startsWith('_')) {
diagnosticLevel = 'none';
}
} else if (decl.node.nodeType === ParseNodeType.Parameter) {
nameNode = decl.node.name;

View File

@ -0,0 +1,21 @@
# This sample tests the reportUnusedVariable diagnostic check.
def func1(a: int):
x = 4
# This should generate an error if reportUnusedVariable is enabled.
y = x
_z = 4
_ = 2
__z__ = 5
if x + 1:
# This should generate an error if reportUnusedVariable is enabled.
z = 3
else:
# This should generate an error if reportUnusedVariable is enabled.
z = 5

View File

@ -1084,3 +1084,15 @@ test('Self2', () => {
TestUtils.validateResults(analysisResults, 5);
});
test('UnusedVariable1', () => {
const configOptions = new ConfigOptions('.');
configOptions.diagnosticRuleSet.reportUnusedVariable = 'none';
const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['unusedVariable1.py'], configOptions);
TestUtils.validateResults(analysisResults1, 0);
configOptions.diagnosticRuleSet.reportUnusedVariable = 'error';
const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['unusedVariable1.py'], configOptions);
TestUtils.validateResults(analysisResults2, 3);
});