|
| 1 | +# Licensed under the MIT: https://mit-license.org/ |
| 2 | +# For details: https://github.com/pylint-dev/pylint-ml/LICENSE |
| 3 | +# Copyright (c) https://github.com/pylint-dev/pylint-ml/CONTRIBUTORS.txt |
| 4 | + |
| 5 | +"""Check for usage of the inefficient pandas DataFrame.iterrows() method.""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +from astroid import nodes |
| 10 | +from pylint.checkers import BaseChecker |
| 11 | +from pylint.checkers.utils import only_required_for_messages |
| 12 | +from pylint.interfaces import HIGH |
| 13 | + |
| 14 | + |
| 15 | +class PandasIterrowsChecker(BaseChecker): |
| 16 | + name = "pandas-iterrows" |
| 17 | + msgs = { |
| 18 | + "W8106": ( |
| 19 | + "Usage of pandas DataFrame.iterrows() detected", |
| 20 | + "pandas-iterrows", |
| 21 | + "Avoid using DataFrame.iterrows() for large datasets. Consider using vectorized operations or " |
| 22 | + ".itertuples() instead.", |
| 23 | + ), |
| 24 | + } |
| 25 | + |
| 26 | + @only_required_for_messages("pandas-iterrows") |
| 27 | + def visit_call(self, node: nodes.Call) -> None: |
| 28 | + if isinstance(node.func, nodes.Attribute): |
| 29 | + method_name = getattr(node.func, "attrname", None) |
| 30 | + if method_name == "iterrows": |
| 31 | + object_name = getattr(node.func.expr, "name", None) |
| 32 | + if object_name and self._is_dataframe_name(object_name): |
| 33 | + self.add_message("pandas-iterrows", node=node, confidence=HIGH) |
| 34 | + |
| 35 | + @staticmethod |
| 36 | + def _is_dataframe_name(name: str) -> bool: |
| 37 | + """Check if the object name suggests it's a DataFrame (e.g., starts with 'df_').""" |
| 38 | + return name.startswith("df_") |
0 commit comments