0

I have a with statement in my code:

@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()

When I run this code, it works fine. However, I was expecting an error to occur because I thought session would be out of the with statement's scope and hence undefined?

I haven't defined session anywhere else within this function or globally.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • 3
    It doesn't go out of scope, but session.close has been called, so you shouldn't try to use it – Matt Mar 24 '15 at 07:17
  • Side note: it would be nice if you followed everybody's convention by following PEP 8 (PEP 257 is also worth knowing). – Eric O. Lebigot Mar 24 '15 at 07:43

1 Answers1

3

Python variables stay within scope until the end of the method. There are no 'blocks' for scope in python

Moshe Carmeli
  • 295
  • 1
  • 5