Note that there are some explanatory texts on larger screens.

plurals
  1. POUse python dict to lookup mutable objects
    primarykey
    data
    text
    <p>I have a bunch of <code>File</code> objects, and a bunch of <code>Folder</code> objects. Each folder has a <code>list</code> of files. Now, sometimes I'd like to lookup which folder a certain file is in. I don't want to traverse over all folders and files, so I create a lookup <code>dict</code> file -> folder.</p> <pre><code>folder = Folder() myfile = File() folder_lookup = {} # This is pseudocode, I don't actually reach into the Folder # object, but have an appropriate method folder.files.append(myfile) folder_lookup[myfile] = folder </code></pre> <p>Now, the problem is, the files are mutable objects. My application is built around the fact. I change properites on them, and the GUI is notified and updated accordingly. Of course you can't put mutable objects in dicts. So what I tried first is to generate a hash based on the current content, basically:</p> <pre><code>def __hash__(self): return hash((self.title, ...)) </code></pre> <p>This didn't work of course, because when the object's contents changed its hash (and thus its identity) changed, and everything got messed up. What I need is an object that keeps its identity, although its contents change. I tried various things, like making <code>__hash__</code> return <code>id(self)</code>, overriding <code>__eq__</code>, and so on, but never found a satisfying solution. One complication is that the whole construction should be pickelable, so that means I'd have to store <code>id</code> on creation, since it could change when pickling, I guess.</p> <p>So I basically want to use the identity of an object (not its state) to quickly look up data related to the object. I've actually found a really nice pythonic workaround for my problem, which I might post shortly, but I'd like to see if someone else comes up with a solution. </p>
    singulars
    1. This table or related slice is empty.
    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.
 

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