我的代码中有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
。
答案 0 :(得分:3)
Python变量保持在范围内,直到方法结束。没有'块'适用于python中的范围