ruff
1ade9a59 - [`pydoclint`] Fix false positive on explicit exception re-raising (`DOC501`, `DOC502`) (#21011)

Commit
69 days ago
[`pydoclint`] Fix false positive on explicit exception re-raising (`DOC501`, `DOC502`) (#21011) ## Summary Fixes #20973 (`docstring-extraneous-exception`) false positive when exceptions mentioned in docstrings are caught and explicitly re-raised using `raise e` or `raise e from None`. ## Problem Analysis The DOC502 rule was incorrectly flagging exceptions mentioned in docstrings as "not explicitly raised" when they were actually being explicitly re-raised through exception variables bound in `except` clauses. **Root Cause**: The `BodyVisitor` in `check_docstring.rs` only checked for direct exception references (like `raise OSError()`) but didn't recognize when a variable bound to an exception in an `except` clause was being re-raised. **Example of the bug**: ```python def f(): """Do nothing. Raises ------ OSError If the OS errors. """ try: pass except OSError as e: raise e # This was incorrectly flagged as not explicitly raising OSError ``` The issue occurred because `resolve_qualified_name(e)` couldn't resolve the variable `e` to a qualified exception name, since `e` is just a variable binding, not a direct reference to an exception class. ## Approach Modified the `BodyVisitor` in `crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs` to: 1. **Track exception variable bindings**: Added `exception_variables` field to map exception variable names to their exception types within `except` clauses 2. **Enhanced raise statement detection**: Updated `visit_stmt` to check if a `raise` statement uses a variable name that's bound to an exception in the current `except` clause 3. **Proper scope management**: Clear exception variable mappings when leaving `except` handlers to prevent cross-contamination **Key changes**: - Added `exception_variables: FxHashMap<&'a str, QualifiedName<'a>>` to track variable-to-exception mappings - Enhanced `visit_except_handler` to store exception variable bindings when entering `except` clauses - Modified `visit_stmt` to check for variable-based re-raising: `raise e` → lookup `e` in `exception_variables` - Clear mappings when exiting `except` handlers to maintain proper scope --------- Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
Author
Parents
Loading