Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does "finally: pass" do in Python? (e.g. in try – except – finally)

I would have assumed a finally clause with only a pass to be pointless.

But in a Bottle template, the following code for an optional include would not work without it.
The result would contain everything before, and the included code itself, but nothing after it.
(See the corresponding question.)

try:
    include(optional_view)
except NameError:
    pass
finally:
    pass

What does finally: pass do, and when is it useful?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

finally: pass does nothing, but you don’t actually have finally: pass. You’re writing a Bottle template, not Python, and you have broken Bottle template syntax.

Bottle templates ignore indentation in inline code, which means they need a different way to tell when a block statement ends. Bottle templates use a special end keyword for this. Your try-except needs an end:

try:
    whatever()
except NameError:
    pass
end

Otherwise, the except block continues, and stuff that wasn’t supposed to go in the except is considered part of the except.

With finally: pass, the stuff that was incorrectly part of the except is now incorrectly part of the finally, so it runs in cases where it wouldn’t have run as part of the except.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading