Rule request
Allow finally block to have simple content only.
It can contain few lines of code, but it shouldn't contain untrivial logic, which can not be understand very quickly at code reading.
Thesis
Correct finally block:
- One-two statements.
- One
if with elif and else w/o sub-blocks.
Wrong finally block:
One bloated with business logic and hard to read.
It's arguable when exactly the watershed should be located.
I propose something like this for correct finally:
- Up to 10 statements.
- Up to 2 levels of indentation (i.e. sub-blocks)
- Maybe up to 10 basic tokens in each statement.
Reasoning
IMO, finally block best suites for code snippets like this:
try:
x = open_something()
y = x.read_value()
...
except SomeError as e:
...
finally:
close_something(x)
It's easy to read and understand what finally block stands for.
But code with big and difficult finally block smells.
My arguments are here:
- Code in
finally block should basically do nothing other than some "cleaning" or "finishing" after try and provide only necessary things. If some code can be located after try-except-finally, it should be located there, and not in finally itself.
- There is an accepted PEP 765 (https://peps.python.org/pep-0765/) which disallow
return/break/continue in finally block for 3.14+. Thus finally is already block with very special rules, we just want to make those rules to be more strict.
- Generated bytecode has two copies of
finally block content on latest CPython versions. As a result, big finally block provide larger code objects.
Rule request
Allow
finallyblock to have simple content only.It can contain few lines of code, but it shouldn't contain untrivial logic, which can not be understand very quickly at code reading.
Thesis
Correct
finallyblock:ifwithelifandelsew/o sub-blocks.Wrong
finallyblock:One bloated with business logic and hard to read.
It's arguable when exactly the watershed should be located.
I propose something like this for correct
finally:Reasoning
IMO,
finallyblock best suites for code snippets like this:It's easy to read and understand what
finallyblock stands for.But code with big and difficult
finallyblock smells.My arguments are here:
finallyblock should basically do nothing other than some "cleaning" or "finishing" aftertryand provide only necessary things. If some code can be located aftertry-except-finally, it should be located there, and not infinallyitself.return/break/continueinfinallyblock for 3.14+. Thusfinallyis already block with very special rules, we just want to make those rules to be more strict.finallyblock content on latest CPython versions. As a result, bigfinallyblock provide larger code objects.