Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean "weakly-referenced object no longer exists"?

Tags:

python

I am running a Python code and I get the following error message:

Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in <bound method crawler.__del__ of <searchengine.crawler instance at 0x2b8c1f99ef80>> ignored 

Does anybody know what can it means?

P.S. This is the code which produce the error:

import sqlite  class crawler:    def __init__(self,dbname):     tmp = sqlite.connect(dbname)     self.con = tmp.cursor()    def __del__(self):     self.con.close()  crawler =  crawler('searchindex.db') 
like image 978
Verrtex Avatar asked Sep 26 '09 20:09

Verrtex


1 Answers

A normal AKA strong reference is one that keeps the referred-to object alive: in CPython, each object keeps the number of (normal) references to it that exists (known as its "reference count" or RC) and goes away as soon as the RC reaches zero (occasional generational mark and sweep passes also garbage-collect "reference loops" once in a while).

When you don't want an object to stay alive just because another one refers to it, then you use a "weak reference", a special variety of reference that doesn't increment the RC; see the docs for details. Of course, since the referred-to object CAN go away if not otherwise referred to (the whole purpose of the weak ref rather than a normal one!-), the referring-to object needs to be warned if it tries to use an object that's gone away -- and that alert is given exactly by the exception you're seeing.

In your code...:

def __init__(self,dbname):     tmp = sqlite.connect(dbname)     self.con = tmp.cursor()  def __del__(self):     self.con.close() 

tmp is a normal reference to the connection... but it's a local variable, so it goes away at the end of __init__. The (peculiarly named) cursor self.con stays, BUT it's internally implemented to only hold a WEAK ref to the connection, so the connection goes away when tmp does. So in __del__ the call to .close fails (since the cursor needs to use the connection in order to close itself).

Simplest solution is the following tiny change:

def __init__(self,dbname):     self.con = sqlite.connect(dbname)     self.cur = self.con.cursor()  def __del__(self):     self.cur.close()     self.con.close() 

I've also taken the opportunity to use con for connection and cur for cursor, but Python won't mind if you're keen to swap those (you'll just leave readers perplexed).

like image 192
Alex Martelli Avatar answered Oct 02 '22 16:10

Alex Martelli