【问题标题】:Using a variable in a try,catch,finally statement without declaring it outside在 try、catch、finally 语句中使用变量而不在外部声明它
【发布时间】:2013-06-16 05:50:10
【问题描述】:

我对 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


    【解决方案1】:

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

    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
    

    这应该确保关闭(请参阅more here)。 在某些情况下,您甚至不需要closing,因为连接最有可能支持上下文协议本身,因此只需with getConnection(database)...

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 是的,我希望这是有道理的,但是“离我们有多远”呢?我会假设一个函数会包含它,那么 if 语句和循环呢?
      • 如果整个块在一个函数内,从那时起直到函数结束都可以使用。如果它在模块级别,则它在该模块中全局可用。 If 语句和循环不会引入新的作用域。
      猜你喜欢
      • 1970-01-01
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 2014-06-23
      相关资源
      最近更新 更多