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.

2
  • 3
    It doesn't go out of scope, but session.close has been called, so you shouldn't try to use it Commented Mar 24, 2015 at 7:17
  • Side note: it would be nice if you followed everybody's convention by following PEP 8 (PEP 257 is also worth knowing). Commented Mar 24, 2015 at 7:43

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments