Using a variable in a try,catch,finally statement

2019-02-02 23:08发布

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()

标签: python scope
2条回答
手持菜刀,她持情操
2楼-- · 2019-02-02 23:49

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.

查看更多
趁早两清
3楼-- · 2019-02-03 00:01

I'd suggest using contexts, like:

from contextlib import closing

try:
    with closing(getConnection(database)) as connection:
        with closing(connection.cursor()) as cursor:
            cursor.execute("some query")
except:
    log.error("Problem")
    raise

This should ensure the closing (see more here). In some cases, you won't even need closing since connection is most likely to support the context protocol itself, so that would be just with getConnection(database)...

查看更多
登录 后发表回答