33

我对 Python 很陌生,这是我正在查看的一些代码:

try:
    connection = getConnection(database)
    cursor = connection.cursor()
    cursor.execute("some query")
except:
    log.error("Problem.")
    raise
finally:
    cursor.close()
    connection.close()

清理得当吗?在我写过的其他语言中,我习惯于做这样的事情:

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

2 回答 2

47

Python 没有块作用域。块内定义的任何内容try都将在外部可用。

也就是说,您仍然会遇到一个问题:如果是getConnection()引发错误的调用,cursor将是未定义的,因此finally块中的引用将出错。

于 2013-06-19T15:48:45.070 回答
8

我建议使用上下文,例如:

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

这应该确保关闭(在此处查看更多信息)。在某些情况下,您甚至不需要closing,因为连接最有可能支持上下文协议本身,所以这只是with getConnection(database)...

于 2013-06-19T15:49:29.313 回答