Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I'm assuming it is not a good idea to return within the try block if there is something happening in the finally block. </p> </blockquote> <p>You're assuming wrong. The whole point of a <code>finally</code> is that it <em>always</em> happens, even if you <code>return</code> or <code>break</code> early or raise an unhandled exception.* And it happens <em>after</em> the <code>return</code>.**</p> <p>This is explained under <a href="http://docs.python.org/3.3/reference/compound_stmts.html#the-try-statement" rel="nofollow">The try statement</a> in the documentation… but that isn't exactly the most novice-friendly section of the docs.</p> <hr> <p>That being said, you seem to be using a <code>finally</code> block to fake an <code>except</code> block. Instead of having a flag that you check at <code>finally</code> time to see if there was an exception, just use the exception itself tell you that there was an exception:</p> <pre><code>def connect(self): try: conn = ftplib.FTP(self.hostname, self.user, self.password) return conn except Exception as e: logging.error('Failed to connect to %s for %s' % (self.hostname, self.user)) raise </code></pre> <hr> <p>* That "always" is really only true within limits. If your program calls some C code that segfaults the interpreter, or you explicitly call <code>_exit</code>, or someone pulls the power cord in the middle of the program, the <code>finally</code> code obviously won't run.</p> <p>** It might more precise to say it's happening in the middle of the <code>return</code>, but I think that just adds confusion; unless you're actually working on the guts of the interpreter, you can think of <code>return</code> as a single step.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload