Re:Python Is Eating the World
by joshuamorton on Monday August 12, 2019 @12:37PM
(#20677064)
Indeed, as another user mentions, mypy will detect this issue, as will pytype, even without any annotations.
Interesting, I had not looked at these because I'm not interested in volunteering to add type notations to our code base.
mypy was able to detect these kinds of issues for me
However, here's a related but different python gotcha:
In this example, v is only defined inside the if. Due to python's limited scopes, v is also valid outside the if, but only has an assignment when foo(a) is True. When foo(a) is false, the for loop throws an NameError. And yes, a coworker wrote code that accidentally implemented this antipattern, albeit much more spread out in the code base.This is clearly a bug in the code, yet no static analysis tools I've tried have successfully discovered it. There's a bug in pylint that's been marked WONTFIX because it requires a wildly different implementation. At a language level, it feels weird that if blocks aren't a scope level for new variables. If you want to reference v outside the if loop, declare / assign it outside the loop first.