3 ms·
Well, this should have been caught as an unused assignment in static analysis. A whole ton of languages allow this situation, so I'm not gonna ding Python too h
by jldugger 7y ago
Well, this should have been caught as an unused assignment in static analysis. A whole ton of languages allow this situation, so I'm not gonna ding Python too hard for that one.
However, here's a related but different python gotcha:
if foo(a):
v = list(bar(a))
for i in v:
print i
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.
- takeda 7y agomypy was able to detect these kinds of issues for me
- joshuamorton 7y agoIndeed, as another user mentions, mypy will detect this issue, as will pytype, even without any annotations.
- jldugger 7y agoInteresting, I had not looked at these because I'm not interested in volunteering to add type notations to our code base.
- marmaduke 7y agoI'm retty sure PyCharm catches that 2nd one with a warning