I'm pretty new to Python, here is some code I am looking at:
try: connection = getConnection(database) cursor = connection.cursor() cursor.execute("some query") except: log.error("Problem.") raise finally: cursor.close() connection.close()
Is that being cleaned up properly? In other languages I have written in, I am used to doing something like this:
connection = None cursor = None try: connection = getConnection(database) cursor = connection.cursor() cursor.execute("some query") except: log.error("Problem.") raise finally: if cursor is not None: cursor.close() if connection is not None: connection.close()
Solution 1 What you need to do is declare your variable outside of the try scope. Before the try scope so it the variable still exists in your except block. This will raise the exception but x will still have scope (lifetime) and will print out in the 2nd exception case.
Variables in try block So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.
Variables declared within the try/catch block are not in scope in the containing block, for the same reason that all other variable declarations are local to the scope in which they occur: That's how the specification defines it. :-) (More below, including a reply to your comment.)
Python does not have block scope. Anything defined inside the try
block will be available outside.
That said, you would still have a problem: if it is the getConnection()
call that raises the error, cursor
will be undefined, so the reference in the finally
block will error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With