[lxml-dev] the subelements of my tree are moving alone

jholg at gmx.de jholg at gmx.de
Wed Mar 11 09:22:41 CET 2009


Hi,
 
> It works perfectly, but it seems that the nodes under the root node (the
> subelements) move sometimes "alone". The tree structure is kept, but the
> address of the elements in memory is changing. As the structure is kept,
> it
> is not a problem for lxml use only: I can walk in the tree, doing what I
> need.

That's true. lxml creates its elements on-the-fly on access, you can think of them as access proxies to the underlying libxml2 tree.
This means they go away when no Python reference to them is kept.
 
> But the problem is that I use this custom tree as the underlying data
> structure for a PyQt custom QTreeWidget. In this widget, I use the
> method "internalPointer()" of QModelIndex instances (as proposed in the
> chapter 16 of book "Rapid GUI Programming with Python
> and Qt" by Mark Summerfield (around p.500)).
> 
> The problem is that if the nodes move, the "internalPointer()" of Qt are
> not
> up to date: I obtain segmentation faults.
> 
> Is this normal that nodes of the tree move in memory *alone*? Is this due
> to
> the garbage collector? If yes, how to keep my pointers up to date?

You could keep elements around by caching them, which is usually done for performance tuning (trading memory for speed), like:

cache[root] = list(root.iter())

This caches the whole tree, see "Caching elements" in the objectify performance section:
http://codespeak.net/lxml/performance.html#lxml-objectify

So essentially you'd need to keep a Python reference to each instantiated element that you want to hand to PyQt.
I wondered why PyQt doesn't keep the Python reference itself, but alas it's just a weak reference:
http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg16046.html

Holger
-- 
Nur bis 16.03.! DSL-Komplettanschluss inkl. WLAN-Modem für nur 
17,95 ¿/mtl. + 1 Monat gratis!* http://dsl.gmx.de/?ac=OM.AD.PD003K11308T4569a


More information about the lxml-dev mailing list