Skip to content

Commit 6b68661

Browse files
Warn about unused type: ignore comments when error code is disabled (#18849)
Fixes #11059
1 parent b6a662c commit 6b68661

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

mypy/errors.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -506,10 +506,13 @@ def add_error_info(self, info: ErrorInfo) -> None:
506506
# line == end_line for most nodes, so we only loop once.
507507
for scope_line in lines:
508508
if self.is_ignored_error(scope_line, info, self.ignored_lines[file]):
509+
err_code = info.code or codes.MISC
510+
if not self.is_error_code_enabled(err_code):
511+
# Error code is disabled - don't mark the current
512+
# "type: ignore" comment as used.
513+
return
509514
# Annotation requests us to ignore all errors on this line.
510-
self.used_ignored_lines[file][scope_line].append(
511-
(info.code or codes.MISC).code
512-
)
515+
self.used_ignored_lines[file][scope_line].append(err_code.code)
513516
return
514517
if file in self.ignored_files:
515518
return

test-data/unit/check-errorcodes.test

+13
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,19 @@ x # type: ignore[name-defined, attr-defined] # E: Unused "type: ignore[attr-defi
105105
# flags: --warn-unused-ignores
106106
"x" # type: ignore[name-defined] # E: Unused "type: ignore" comment [unused-ignore]
107107

108+
[case testErrorCodeWarnUnusedIgnores7_WarnWhenErrorCodeDisabled]
109+
# flags: --warn-unused-ignores --disable-error-code name-defined
110+
x # type: ignore # E: Unused "type: ignore" comment [unused-ignore]
111+
x # type: ignore[name-defined] # E: Unused "type: ignore" comment [unused-ignore]
112+
"x".foobar(y) # type: ignore[name-defined, attr-defined] # E: Unused "type: ignore[name-defined]" comment [unused-ignore]
113+
114+
[case testErrorCodeWarnUnusedIgnores8_IgnoreUnusedIgnore]
115+
# flags: --warn-unused-ignores --disable-error-code name-defined
116+
"x" # type: ignore[unused-ignore]
117+
"x" # type: ignore[name-defined, unused-ignore]
118+
"x" # type: ignore[xyz, unused-ignore]
119+
x # type: ignore[name-defined, unused-ignore]
120+
108121
[case testErrorCodeMissingWhenRequired]
109122
# flags: --enable-error-code ignore-without-code
110123
"x" # type: ignore # E: "type: ignore" comment without error code [ignore-without-code]

0 commit comments

Comments
 (0)