Search code examples
pythonpymysql

pymysql cursor doesn't close


In the PyMySQL library, in cursors.py the following functions are called:

def __enter__(self):
  return self

def __exit__(self, *exc_info):
  del exc_info
  self.close()

That's mean that if I use the cursor class in the with statement, the cursor should close whenever I go out from the nested block. Why instead it remain setted?

db = pymysql.connect(config)

with pymysql.cursors.Cursor(db) as cursor:
    print(cursor)

print(cursor)

also:

db = pymysql.connect(config)

with db.cursor() as cursor:
    print(cursor)

print(cursor)

both forms return the cursor object printing two times (one time inside the with statement and one time out from the with statement?. Am I doing something wrong?


Solution

  • Closing a cursor doesn't null out the cursor, just detaches it from the database. Try printing cursor.connection instead.

    Also, I think you're expecting the "with" keyword to delete the object in question, but it's really just syntactic sugar around the enter and exit functions.