سؤال

def connect(self):
    ok = False
    try:
        conn = ftplib.FTP(self.hostname, self.user, self.password)
        ok = True
        return conn
    finally:
        if not ok:
            logging.error('Failed to connect to %s for %s' % (self.hostname, self.user))

I'm assuming it is not a good idea to return within the try block if there is something happening in the finally block. I just want to be sure of the order of execution before I slam someones head!

هل كانت مفيدة؟

المحلول

I'm assuming it is not a good idea to return within the try block if there is something happening in the finally block.

You're assuming wrong. The whole point of a finally is that it always happens, even if you return or break early or raise an unhandled exception.* And it happens after the return.**

This is explained under The try statement in the documentation… but that isn't exactly the most novice-friendly section of the docs.


That being said, you seem to be using a finally block to fake an except block. Instead of having a flag that you check at finally time to see if there was an exception, just use the exception itself tell you that there was an exception:

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

* That "always" is really only true within limits. If your program calls some C code that segfaults the interpreter, or you explicitly call _exit, or someone pulls the power cord in the middle of the program, the finally code obviously won't run.

** It might more precise to say it's happening in the middle of the return, but I think that just adds confusion; unless you're actually working on the guts of the interpreter, you can think of return as a single step.

نصائح أخرى

Rest assured the finally block is always executed. The return in the try block doesn't change that. No head slamming required ;-)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top