pylint
pylint copied to clipboard
Extend possibly-used-before-assignment to definitions in try then used in finally or after
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!
Thanks @lbenezriravin This makes sense.
Closing as duplicate of #5524
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 thetry
block.
Implementation tip: when checking whether the except handlers define a name, raise, or return, consider using NamesConsumer._defines_name_raises_or_returns()
from #5764
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)