Bug #76181 ReferenceError: weakly-referenced object no longer exists
Submitted: 5 Mar 2015 19:30 Modified: 3 Aug 2022 15:14
Reporter: Trevor Carlson Email Updates:
Status: Closed Impact on me:
None 
Category:Connector / Python Severity:S4 (Feature request)
Version:2.0.3 OS:Any
Assigned to: CPU Architecture:Any

[5 Mar 2015 19:30] Trevor Carlson
Description:
Just look at the repeat section.

I'm using Python 2.7.6 on Windows, connector 2.0.3, and MySQL 5.6.20 on Linux.

I checked 2.1.1, and the relevant code has not changed.

How to repeat:
def get_cursor():
    return mysql.connector.connect().cursor()
get_cursor().execute("select sleep(1)")

Will result in
Traceback (most recent call last):
  File "X.py", line 62, in <module>
    get_cursor().execute("select sleep(1)")
  File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 476, in execute
    if not self._connection:
ReferenceError: weakly-referenced object no longer exists

It does this because the connector only lives until the function returns. The cursor only has a weak reference.

Suggested fix:
While it may be acceptable to only have a weak reference from the cursor to the parent connection, this is the wrong error message. The code in question should raise the "Cursor is not connected." error within the checking code.

Possible fix is to modify _set_connection():
            def collect(*args):
                self._connection = None
            self._connection = weakref.proxy(connection, collect)
This way, once the connection is destroyed, it will be reset to None, and the relevant None-checking code will no longer break.
[17 Jul 2015 10:00] Andrii Nikitin
I don't think that current behavior may be claimed to be a bug.

But since the suggestion looks relevant, I verified it as 'Feature Request'.
[17 Jul 2015 17:12] Trevor Carlson
For reference, my perspective here is that "weakly-referenced object no longer exists" is not a useful error message. I encountered it while converting some old code, and tracking down the issue was much harder than it would have been if the error had been "Cursor is not connected" or similar.
[3 Aug 2022 15:14] Philip Olson
Posted by developer:
 
Fixed as of the upcoming MySQL Connector/Python 8.0.31 release, and here's the proposed changelog entry from the documentation team:

Destroying a connection object now raises a ProgrammingError exception
stating the cursor is not connected. Before it raised a ReferenceError
exception about weakly-referenced objects, which related to how cursors
contain a weak reference to the connection.

Thank you for the bug report.