We should forbid using try block with anything other than except.
Related: https://help.semmle.com/wiki/display/PYTHON/Should+use+a+%27with%27+statement
Let's remember why do we use try with finally. To clean thing up when something explodes inside try block. That a popular pattern for files, streams, etc.
What else can be used in this case? We can use with to make this code readable. Consider this example:
try:
f = open("filename")
f.write(...)
finally:
f.close()
Versus context manager:
with open("filename") as f:
f.write(...)
The second version looks cleaner and more readable.
This rule is limited to cases when there are no except blocks. Because when there are except blocks finally becomes very useful to execute any logic after both successful and exceptional branches.
@novikovfred do you have the time to take this one? Should be a really simple one.
@sobolevn ye, i'll do it
Most helpful comment
@sobolevn ye, i'll do it