|
| 1 | +# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html |
| 2 | +# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE |
| 3 | +# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt |
| 4 | + |
| 5 | +"""Function checker for Python code.""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from itertools import chain |
| 10 | + |
| 11 | +from astroid import nodes |
| 12 | + |
| 13 | +from pylint.checkers import utils |
| 14 | +from pylint.checkers.base.basic_checker import _BasicChecker |
| 15 | + |
| 16 | + |
| 17 | +class FunctionChecker(_BasicChecker): |
| 18 | + """Check if a function definition handles possible side effects.""" |
| 19 | + |
| 20 | + msgs = { |
| 21 | + "W0135": ( |
| 22 | + "The context used in function %r will not be exited.", |
| 23 | + "contextmanager-generator-missing-cleanup", |
| 24 | + "Used when a contextmanager is used inside a generator function" |
| 25 | + " and the cleanup is not handled.", |
| 26 | + ) |
| 27 | + } |
| 28 | + |
| 29 | + @utils.only_required_for_messages("contextmanager-generator-missing-cleanup") |
| 30 | + def visit_functiondef(self, node: nodes.FunctionDef) -> None: |
| 31 | + self._check_contextmanager_generator_missing_cleanup(node) |
| 32 | + |
| 33 | + @utils.only_required_for_messages("contextmanager-generator-missing-cleanup") |
| 34 | + def visit_asyncfunctiondef(self, node: nodes.AsyncFunctionDef) -> None: |
| 35 | + self._check_contextmanager_generator_missing_cleanup(node) |
| 36 | + |
| 37 | + def _check_contextmanager_generator_missing_cleanup( |
| 38 | + self, node: nodes.FunctionDef |
| 39 | + ) -> None: |
| 40 | + """Check a FunctionDef to find if it is a generator |
| 41 | + that uses a contextmanager internally. |
| 42 | +
|
| 43 | + If it is, check if the contextmanager is properly cleaned up. Otherwise, add message. |
| 44 | +
|
| 45 | + :param node: FunctionDef node to check |
| 46 | + :type node: nodes.FunctionDef |
| 47 | + """ |
| 48 | + # if function does not use a Yield statement, it cant be a generator |
| 49 | + with_nodes = list(node.nodes_of_class(nodes.With)) |
| 50 | + if not with_nodes: |
| 51 | + return |
| 52 | + # check for Yield inside the With statement |
| 53 | + yield_nodes = list( |
| 54 | + chain.from_iterable( |
| 55 | + with_node.nodes_of_class(nodes.Yield) for with_node in with_nodes |
| 56 | + ) |
| 57 | + ) |
| 58 | + if not yield_nodes: |
| 59 | + return |
| 60 | + |
| 61 | + # infer the call that yields a value, and check if it is a contextmanager |
| 62 | + for with_node in with_nodes: |
| 63 | + for call, held in with_node.items: |
| 64 | + if held is None: |
| 65 | + # if we discard the value, then we can skip checking it |
| 66 | + continue |
| 67 | + |
| 68 | + # safe infer is a generator |
| 69 | + inferred_node = getattr(utils.safe_infer(call), "parent", None) |
| 70 | + if not isinstance(inferred_node, nodes.FunctionDef): |
| 71 | + continue |
| 72 | + if self._node_fails_contextmanager_cleanup(inferred_node, yield_nodes): |
| 73 | + self.add_message( |
| 74 | + "contextmanager-generator-missing-cleanup", |
| 75 | + node=node, |
| 76 | + args=(node.name,), |
| 77 | + ) |
| 78 | + |
| 79 | + @staticmethod |
| 80 | + def _node_fails_contextmanager_cleanup( |
| 81 | + node: nodes.FunctionDef, yield_nodes: list[nodes.Yield] |
| 82 | + ) -> bool: |
| 83 | + """Check if a node fails contextmanager cleanup. |
| 84 | +
|
| 85 | + Current checks for a contextmanager: |
| 86 | + - only if the context manager yields a non-constant value |
| 87 | + - only if the context manager lacks a finally, or does not catch GeneratorExit |
| 88 | +
|
| 89 | + :param node: Node to check |
| 90 | + :type node: nodes.FunctionDef |
| 91 | + :return: True if fails, False otherwise |
| 92 | + :param yield_nodes: List of Yield nodes in the function body |
| 93 | + :type yield_nodes: list[nodes.Yield] |
| 94 | + :rtype: bool |
| 95 | + """ |
| 96 | + |
| 97 | + def check_handles_generator_exceptions(try_node: nodes.Try) -> bool: |
| 98 | + # needs to handle either GeneratorExit, Exception, or bare except |
| 99 | + for handler in try_node.handlers: |
| 100 | + if handler.type is None: |
| 101 | + # handles all exceptions (bare except) |
| 102 | + return True |
| 103 | + inferred = utils.safe_infer(handler.type) |
| 104 | + if inferred and inferred.qname() in { |
| 105 | + "builtins.GeneratorExit", |
| 106 | + "builtins.Exception", |
| 107 | + }: |
| 108 | + return True |
| 109 | + return False |
| 110 | + |
| 111 | + # if context manager yields a non-constant value, then continue checking |
| 112 | + if any( |
| 113 | + yield_node.value is None or isinstance(yield_node.value, nodes.Const) |
| 114 | + for yield_node in yield_nodes |
| 115 | + ): |
| 116 | + return False |
| 117 | + # if function body has multiple Try, filter down to the ones that have a yield node |
| 118 | + try_with_yield_nodes = [ |
| 119 | + try_node |
| 120 | + for try_node in node.nodes_of_class(nodes.Try) |
| 121 | + if any(try_node.nodes_of_class(nodes.Yield)) |
| 122 | + ] |
| 123 | + if not try_with_yield_nodes: |
| 124 | + # no try blocks at all, so checks after this line do not apply |
| 125 | + return True |
| 126 | + # if the contextmanager has a finally block, then it is fine |
| 127 | + if all(try_node.finalbody for try_node in try_with_yield_nodes): |
| 128 | + return False |
| 129 | + # if the contextmanager catches GeneratorExit, then it is fine |
| 130 | + if all( |
| 131 | + check_handles_generator_exceptions(try_node) |
| 132 | + for try_node in try_with_yield_nodes |
| 133 | + ): |
| 134 | + return False |
| 135 | + return True |
0 commit comments