2014-09-13 74 views
2

通過使用MySQL官方Python驅動程序mysql.connector,以下代碼片段正常工作。MySQL中weakref的用途mysql.connector.cursor

# -*- coding: utf-8 -*- 

import mysql.connector 

conn = mysql.connector.connect(...) 
cursor = conn.cursor() 

cursor.execute(...) 

然而,當我使用鏈式調用來創建光標,

# -*- coding: utf-8 -*- 

import mysql.connector 

cursor = mysql.connector.connect(...).cursor() 

cursor.execute(...) 

我得到異常:的ReferenceError:弱引用的對象不再存在

這是由於使用的weakref in mysql.connector.cursor源代碼

def _set_connection(self, connection): 
    """Set the connection""" 
    try: 
     self._connection = weakref.proxy(connection) 
     self._connection._protocol # pylint: disable=W0212,W0104 
    except (AttributeError, TypeError): 
     raise errors.InterfaceError(errno=2048) 

的weakref不會增加引用計數到臨時連接對象,使語句之後

mysql.connector.connect(...).cursor() 

連接對象似乎是由垃圾收集回收。

由於在mysql.connector.connection源代碼中,沒有對遊標對象的引用。

可能不會設置mysql.connector.cursor中的weakref來解決循環引用問題。

有誰知道爲什麼要設置weakref引用遊標的連接?

謝謝。

回答

2

如果你檢查項目的修訂歷史記錄,the commit that introduces the use of weakref乾脆這樣說:

  • Most objects now use weak references: there was no bug or leak which showed we needed to doso however. Can be revereted.

如此看來,這只是一個預防性的決定,以避免潛在錯誤或泄漏,而不是解決的變化一個具體問題。

+0

您是否使用'bzr annotate'來查找提交? – unutbu 2014-09-13 15:24:32

+1

@unutbu我實際上在Launchpad源代碼查看器中使用了「查看修訂信息」選項,但我確信只是在封面下使用了'bzr annotate'。 – dano 2014-09-13 15:27:44

+0

@dano 我沒有注意到啓動板有完整的提交歷史記錄。 謝謝。 – iconvinced 2014-09-13 16:44:56