Wemake-python-styleguide: Forbid `try` with `finally`without `except`

Created on 5 Oct 2018  路  2Comments  路  Source: wemake-services/wemake-python-styleguide

Rule request

Thesis

We should forbid using try block with anything other than except.

Reasoning

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.

Limitations

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.

Hacktoberfest help wanted starter rule request

Most helpful comment

@sobolevn ye, i'll do it

All 2 comments

@novikovfred do you have the time to take this one? Should be a really simple one.

@sobolevn ye, i'll do it

Was this page helpful?
0 / 5 - 0 ratings