From 620347af428358459c3781223959806c0496dee7 Mon Sep 17 00:00:00 2001 From: Pierre Sassoulas Date: Sat, 9 Apr 2022 19:27:37 +0200 Subject: [PATCH] Suppress `unsubscriptable-object` warnings in type-checking blocks (#5720) * Add a regression test for issue #3979 * Don't emit `unsubscriptable-object` for statements in type-checking blocks Co-authored-by: Jacob Walls --- ChangeLog | 5 +++++ doc/whatsnew/2.14.rst | 5 +++++ pylint/checkers/typecheck.py | 6 +++++- tests/functional/r/regression_02/regression_3979.py | 13 +++++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/functional/r/regression_02/regression_3979.py diff --git a/ChangeLog b/ChangeLog index d6b71e6c28..71c9142c0e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -62,6 +62,11 @@ Release date: TBA Closes #4525 +* Fix false positive for ``unsubscriptable-object`` in Python 3.8 and below for + statements guarded by ``if TYPE_CHECKING``. + + Closes #3979 + * Fix false negative for ``no-member`` when attempting to assign an instance attribute to itself without any prior assignment. diff --git a/doc/whatsnew/2.14.rst b/doc/whatsnew/2.14.rst index ce3c1cedfe..5ffb55052e 100644 --- a/doc/whatsnew/2.14.rst +++ b/doc/whatsnew/2.14.rst @@ -81,6 +81,11 @@ Other Changes Closes #5205 +* Fix false positive for ``unsubscriptable-object`` in Python 3.8 and below for + statements guarded by ``if TYPE_CHECKING``. + + Closes #3979 + * Fix false negative for ``no-member`` when attempting to assign an instance attribute to itself without any prior assignment. diff --git a/pylint/checkers/typecheck.py b/pylint/checkers/typecheck.py index 2ab5ced330..5b3c6a372e 100644 --- a/pylint/checkers/typecheck.py +++ b/pylint/checkers/typecheck.py @@ -1951,7 +1951,11 @@ def visit_subscript(self, node: nodes.Subscript) -> None: return # It would be better to handle function # decorators, but let's start slow. - if supported_protocol and not supported_protocol(inferred, node): + if ( + supported_protocol + and not supported_protocol(inferred, node) + and not utils.in_type_checking_block(node) + ): self.add_message(msg, args=node.value.as_string(), node=node.value) @check_messages("dict-items-missing-iter") diff --git a/tests/functional/r/regression_02/regression_3979.py b/tests/functional/r/regression_02/regression_3979.py new file mode 100644 index 0000000000..4fb0c5a051 --- /dev/null +++ b/tests/functional/r/regression_02/regression_3979.py @@ -0,0 +1,13 @@ +""" +Regression test for https://github.com/PyCQA/pylint/issues/3979 +""" + +import os +from typing import TYPE_CHECKING, Any, Union + +if TYPE_CHECKING: + BasePathLike = os.PathLike[Any] # <-- pylint used to emit E1136 here +else: + BasePathLike = os.PathLike + +foo: Union[str, BasePathLike] = "bar"