diff --git a/ChangeLog b/ChangeLog index 2953c4b0d5..308ac7256c 100644 --- a/ChangeLog +++ b/ChangeLog @@ -21,6 +21,10 @@ Release date: TBA Close #3161 +* ``consider-using-sys-exit`` is no longer emitted when `exit` is imported in the local scope. + + Close #3147 + What's New in Pylint 2.4.2? =========================== diff --git a/pylint/checkers/refactoring.py b/pylint/checkers/refactoring.py index 7e5a8d1407..28313439a4 100644 --- a/pylint/checkers/refactoring.py +++ b/pylint/checkers/refactoring.py @@ -686,13 +686,20 @@ def visit_call(self, node): self._check_consider_using_comprehension_constructor(node) self._check_quit_exit_call(node) + @staticmethod + def _has_exit_in_scope(scope): + exit_func = scope.locals.get("exit") + return bool( + exit_func and isinstance(exit_func[0], (astroid.ImportFrom, astroid.Import)) + ) + def _check_quit_exit_call(self, node): + if isinstance(node.func, astroid.Name) and node.func.name in BUILTIN_EXIT_FUNCS: - # If we have `exit` imported from `sys` in the scope, exempt this instance. - scope = node.root() - exit_func = scope.locals.get("exit") - if exit_func and isinstance( - exit_func[0], (astroid.ImportFrom, astroid.Import) + # If we have `exit` imported from `sys` in the current or global scope, exempt this instance. + local_scope = node.scope() + if self._has_exit_in_scope(local_scope) or self._has_exit_in_scope( + node.root() ): return self.add_message("consider-using-sys-exit", node=node) diff --git a/tests/functional/c/consider_using_sys_exit_local_scope.py b/tests/functional/c/consider_using_sys_exit_local_scope.py new file mode 100644 index 0000000000..05b57ae412 --- /dev/null +++ b/tests/functional/c/consider_using_sys_exit_local_scope.py @@ -0,0 +1,5 @@ +# pylint: disable=missing-docstring,import-outside-toplevel,redefined-builtin + +def run(): + from sys import exit + exit()