Skip to content

False positive on F811 "Redefinition of unused" when using contextlib.suppress #12309

@masklinn

Description

@masklinn

I assume this is a generalised problem with context managers being able to influence control flow but I figure contextlib.suppress could be special-cased maybe?

import contextlib

foo = None
with contextlib.suppress(ImportError):
    from some_module import foo


bar = None
try:
    from some_module import bar
except ImportError:
    pass

print(foo, bar)

the two bits setting "foo" and "bar" are functionally equivalent, but in the first one Ruff reports

test.py:5:29: F811 Redefinition of unused `foo` from line 3
  |
3 | foo = None
4 | with contextlib.suppress(ImportError):
5 |     from some_module import foo
  |                             ^^^ F811
  |
  = help: Remove definition: `foo`

while the second one works fine.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions