wemake-python-styleguide: Forbid to use variables from conditional blocks
Rule request
Thesis
This code does not raise a single violation that x might not be defined:
try:
function_that_raises()
x = 1
except:
...
print(x)
One more example:
if False:
x = 1
print(x)
With for:
for i in []:
x = 0
print(x)
With while:
while False:
x = 0
print(x)
Reasoning
We need to forbid to use variables that are only defined in try, if, for body.
It might not be defined at all. mypy also does not complain about it.
Cases like:
x = 0
try:
function_that_raises()
x = 1
except:
...
print(x)
are fine.
About this issue
- Original URL
- State: open
- Created 5 years ago
- Comments: 24 (21 by maintainers)
@sobolevn I’ll be able to continue soon. That’s what I have to do:
SafeVarsclass to reduce the complexity of the codeI have a few questions, but I’ll ask them when I get back. Sorry for long pauses.
I am almost done with
SafeVarsclass that collects variable assignments for a given node and reduces them to a set of safe variables. But there are cases I still haven’t covered.The next step will be implementation of visitor with this logic:
e.g.
@sobolevn Sorry, I had to pause due lack of time. Fortunately, I will be able to continue during this week.
I am working on prototype for the issue, and I already have implemented
safe_varscollector forFor, AyncFor, If, While, FunctionDef, AsyncFunctionDef, ClassDef, Modulescopes. Progress can be found hereAnd