在 try-catch-finally 语句中使用变量而不在外部声明它

问题描述 投票:0回答:2

我对 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()
python scope
2个回答
53
投票

Python 没有块作用域。

try
块内定义的任何内容都可以在外部使用。

也就是说,您仍然会遇到问题:如果是

getConnection()
调用引发了错误,则
cursor
将是未定义的,因此
finally
块中的引用将会出错。


11
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.