Python中变量的范围" with"声明

时间:2015-03-24 07:03:14

标签: python flask with-statement

我的代码中有with语句:

@app.route('/users', methods = ['POST'])
def registerUser():

    ....

    if email is None:
        errorsList.append(Error("email","Email address not entered"))
    else:       
        # Check if email address is already in database
        with contextlib.closing(DBSession()) as session:        
            if session.query(USER).filter_by(USEREMAIL=email).count():
                errorsList.append(Error("email","This email address already exists"))

    # Add user to database
    user = USER(email,password)
    session.add(user)
    session.commit()

当我运行此代码时,它工作正常。但是,我原以为会发生错误,因为我认为session会超出with语句的范围,因此会undefined

我没有在此功能中的任何其他位置或全局定义session

1 个答案:

答案 0 :(得分:3)

Python变量保持在范围内,直到方法结束。没有'块'适用于python中的范围