Skip to content

False positive F821 and F841 for an exception object inside a lambda function #14521

@dqd

Description

@dqd

Hello, when I run ruff on this code sample, I get F821 and F841 errors:

try:
    raise Exception("test")
except Exception as e:
    print((lambda: e)())

This is the exact output of the ruff check sample.py command (using the current ruff version, i.e. 0.7.4):

sample.py:3:21: F841 [*] Local variable `e` is assigned to but never used
  |
1 | try:
2 |     raise Exception("test")
3 | except Exception as e:
  |                     ^ F841
4 |     print((lambda: e)())
  |
  = help: Remove assignment to unused variable `e`

sample.py:4:20: F821 Undefined name `e`
  |
2 |     raise Exception("test")
3 | except Exception as e:
4 |     print((lambda: e)())
  |                    ^ F821
  |

Found 2 errors.
[*] 1 fixable with the `--fix` option.

I believe that this is a false positive, as this code runs fine on cPython 3.9. It prints "test".

Metadata

Metadata

Assignees

No one assigned

    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