Python 在try、catch、finally语句中使用变量而不在外部声明
我对Python非常陌生,下面是我正在查看的一些代码:Python 在try、catch、finally语句中使用变量而不在外部声明,python,scope,Python,Scope,我对Python非常陌生,下面是我正在查看的一些代码: try: connection = getConnection(database) cursor = connection.cursor() cursor.execute("some query") except: log.error("Problem.") raise finally: cursor.close() connection.close() 清理得好吗?在我用过的其他语
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没有块作用域。
try
块中定义的任何内容都将在外部可用
也就是说,您仍然会遇到一个问题:如果是
getConnection()
调用引发了错误,游标将是未定义的,因此finally
块中的引用将出错。我建议使用上下文,例如:
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
这应确保关闭(请参阅)。
在某些情况下,您甚至不需要关闭,因为连接最有可能支持上下文协议本身,所以使用getConnection(database)只需关闭。
对,我希望这是有意义的,但是“有多远”呢?我假设一个函数将包含它,那么if语句和循环呢?如果整个块都在一个函数中,那么从那时起直到函数结束它都是可用的。如果它在模块级别,则在该模块中全局可用。If语句和循环不引入新的作用域。