pylint icon indicating copy to clipboard operation
pylint copied to clipboard

Extend possibly-used-before-assignment to definitions in try then used in finally or after

Open lbenezriravin opened this issue 5 years ago • 5 comments

Potentially related to #2615. Not sure if these would both be fixed by the same patch, so I'm making a new issue.

Is your feature request related to a problem? Please describe

The following code passes pylint:

try:
   foo = 1 / 0
except:
   pass
print(foo)

But raises an UnboundLocalError when run.

Describe the solution you'd like

Pylint already has an undefined-loop-variable warning for a similar case that could result in the same error:

for foo in []:
    pass
print(foo)

I feel that the former code should raise a warning if that latter code does. More generally, I don't expect UnboundLocalError from any code that passes pylint, but I'm not sure if that guarantee is possible.

Additional context

Thanks for your work on this tool!

lbenezriravin avatar Mar 25 '19 19:03 lbenezriravin

Thanks @lbenezriravin This makes sense.

PCManticore avatar Mar 27 '19 11:03 PCManticore

Closing as duplicate of #5524

Pierre-Sassoulas avatar Jan 09 '22 18:01 Pierre-Sassoulas

This was actually not a duplicate see: https://github.com/PyCQA/pylint/pull/5764#issuecomment-1032803372.

A very relevant comment was made by @cdce8p in #5524 here:

Another idea. I like how pyright names it. Maybe possibly-unbound?

"a" is possibly unbound

Maybe consider-using-try-else

We shouldn't really "force" users to add an else case. There are just to many alternatives. You could for example assign a default value before you enter the try block.

DanielNoord avatar Feb 08 '22 21:02 DanielNoord

Implementation tip: when checking whether the except handlers define a name, raise, or return, consider using NamesConsumer._defines_name_raises_or_returns() from #5764

jacobtylerwalls avatar Feb 08 '22 22:02 jacobtylerwalls

pyright has possibly unbound, mypy has possibly-undefined, I think we should introduce either one of those two names in pylint on top of undefined-variable (maybe possibly-undefined-variable for consistency)

Pierre-Sassoulas avatar Mar 24 '24 21:03 Pierre-Sassoulas