Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

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

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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;-).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...