flake8-bugbear icon indicating copy to clipboard operation
flake8-bugbear copied to clipboard

Detect: 'variable_name' in the try block with 'except ImportError' should also be defined in the except block

Open simon-liebehenschel opened this issue 3 years ago • 2 comments

Correct code:

try:
    from foo import bar
    from spam import eggs
except ImportError:
    from another_foo import bar
    from another_spam import eggs

Bad code:

try:
    from foo import bar
    from spam import eggs
except ImportError:
    # [ Missing import for `bar` ]
    from another_spam import eggs

PyCharm IDE gives a nice warning:

'variable_name' in the try block with 'except ImportError' should also be defined in the except block

Flake8 does not detect this problem.

simon-liebehenschel avatar Mar 01 '22 19:03 simon-liebehenschel

I don't know if we can always cleanly detect this and if it would be high signal. Someone could also do:

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

def some_function():
    if bar:
        do_something()

Adding this would create noise here for some users.

cooperlees avatar Mar 02 '22 21:03 cooperlees

Adding this would create noise here for some users.

Is there an easy way to add opt-in checks? In other words, that are disabled by default, but can be enabled via include=<ERROR_CODE>,

UPD:

Sorry, there is already --extend-select command. I forgot about it. Maybe this warning can be implemented as optional.

simon-liebehenschel avatar Mar 02 '22 21:03 simon-liebehenschel