Weak references and tracebacks

Fernando Pérez fperez528 at yahoo.com
Sat Apr 13 21:16:53 EDT 2002


Is it ok to use weak references to hold tracebacks without generating circular 
references? From the documentation:

Warning:
Assigning the traceback return value to a
  local variable in a function that is handling an exception will
  cause a circular reference.  This will prevent anything referenced
  by a local variable in the same function or by the traceback from
  being garbage collected.  Since most functions don't need access to
  the traceback, the best solution is to use something like
  type, value = sys.exc_info()[:2] to extract only the
  exception type and value. If you do need the traceback, make sure
  to delete it after use (best done with a try ... finally statement) or to 
call exc_info() in
  a function that does not itself handle an exception. Note:
Beginning
  with Python 2.2, such cycles are automatically reclaimed when garbage
  collection is enabled and they become unreachable, but it remains more
  efficient to avoid creating cycles.

So I'm wondering if the following is ok:

type,value,tb=sys.exc_info()
tb_ref = weakref.ref(tb)
del tb

... and then I can keep tb_ref around without this being a problem.

Thanks for any help,

f.



More information about the Python-list mailing list