Python "with" 语句中的变量范围

Scope of variable in Python "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

Python 变量保持在范围内,直到方法结束。 python

范围内没有 'blocks'