Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: ambiguities when (un-)pickling a dict-based tree
    primarykey
    data
    text
    <p>I have a simple tree structure where each node can have several children which are accessed through keys (+ some payload stored in <code>value</code>):</p> <pre><code>class NodeDict(dict): def __init__(self, parent): self.parent = parent self.value = None def AddChild(self, label): self[label] = NodeDict(self) return self[label] class TreeDict: def __init__(self): self.root = NodeDict(None) def ToString(self, level, node): res = ":" + str(node.value) + "\n" for k, v in node.items(): res += " "*level + str(k) + self.ToString(level + 1, v) return res def __str__(self): return self.ToString(1, self.root) </code></pre> <p>When I try to pickle such a tree I have the problem that it is not correctly unpickled as the following example shows:</p> <pre><code>class Obj: def __init__(self, v): self.v = v def __str__(self): return str(self.v) t = TreeDict() a = t.root.AddChild(Obj("A")) b = a.AddChild(Obj("B")) c = b.AddChild(Obj("C")) d = b.AddChild(Obj("D")) e = a.AddChild(Obj("E")) print t import cPickle cPickle.dump(t, open("test.dat", "w")) t = cPickle.load(open("test.dat", "r")) print t </code></pre> <p>The tree looks like this before</p> <pre><code>:None A:None E:None B:None C:None D:None </code></pre> <p>and like this after pickling and unpickling:</p> <pre><code>:None A:None B:None B:None D:None C:None E:None E:None </code></pre> <p>The problem arises from the fact that I am using <code>Obj</code> as <code>label</code>s in the tree (i.e. as keys in the <code>dict</code>). (It also fails when using e.g. strings instead of <code>Obj</code> if they are not all mutually different.) </p> <p>How could this be changed to work as intended?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload