Respect dummy-variable-rgx for unused bound exceptions (#6492)

## Summary

This PR respects our unused variable regex when flagging bound
exceptions, so that you no longer get a violation for, e.g.:

```python
def f():
    try:
        pass
    except Exception as _:
        pass
```

This is an odd pattern, but I think it's surprising that the regex
_isn't_ respected here.

Closes https://github.com/astral-sh/ruff/issues/6391

## Test Plan

`cargo test`
This commit is contained in:
Charlie Marsh 2023-08-11 00:02:02 -04:00 committed by GitHub
parent 563374503f
commit cc151c35a8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 38 additions and 5 deletions

View file

@ -145,3 +145,9 @@ def f() -> None:
obj = Foo()
obj.do_thing()
def f():
try:
pass
except Exception as _:
pass

View file

@ -18,7 +18,13 @@ pub(crate) fn bindings(checker: &mut Checker) {
for binding in checker.semantic.bindings.iter() {
if checker.enabled(Rule::UnusedVariable) {
if binding.kind.is_bound_exception() && !binding.is_used() {
if binding.kind.is_bound_exception()
&& !binding.is_used()
&& !checker
.settings
.dummy_variable_rgx
.is_match(binding.name(checker.locator))
{
let mut diagnostic = Diagnostic::new(
pyflakes::rules::UnusedVariable {
name: binding.name(checker.locator).to_string(),

View file

@ -312,10 +312,13 @@ pub(crate) fn unused_variable(checker: &Checker, scope: &Scope, diagnostics: &mu
&& !binding.is_global()
&& !binding.is_used()
&& !checker.settings.dummy_variable_rgx.is_match(name)
&& name != "__tracebackhide__"
&& name != "__traceback_info__"
&& name != "__traceback_supplement__"
&& name != "__debuggerskip__"
&& !matches!(
name,
"__tracebackhide__"
| "__traceback_info__"
| "__traceback_supplement__"
| "__debuggerskip__"
)
{
return Some((name.to_string(), binding.range, binding.source));
}

View file

@ -256,4 +256,22 @@ F841_0.py:127:21: F841 Local variable `value` is assigned to but never used
|
= help: Remove assignment to unused variable `value`
F841_0.py:152:25: F841 [*] Local variable `_` is assigned to but never used
|
150 | try:
151 | pass
152 | except Exception as _:
| ^ F841
153 | pass
|
= help: Remove assignment to unused variable `_`
Fix
149 149 | def f():
150 150 | try:
151 151 | pass
152 |- except Exception as _:
152 |+ except Exception:
153 153 | pass