A dict like this is the wrong place to keep widgets alive. Widgets belong to 
other objects, probably the container they reside in. The mission of this dict 
is to trigger an action when a widget has been clicked. A widget that does not 
exist anymore can't be clicked in the first place, a widget that gets garbage 
collected also gets removed from screen.

So, id(it) is a safe pattern, and less prone to memory leaks than using widgets 
as keys.


On 10/15/11 5:02 PM Edward K. Ream wrote:

On Sat, Oct 15, 2011 at 3:10 AM, Ville M. Vainio <[email protected]> wrote:
> I don't see a point in doing that in a subclass, since you only need
> to hash so rarely.

Thanks for your comments. They have kept alive a hidden question.

The timing is interesting. I am now in possession of a .leo file that
will reliably take Python down in a specific set of circumstances.
I'm going to get to the bottom of that file, but not here :-)

At first glance, replacing d[w] by d[id(w)], where d is a dict and w
is any widget, seems perfectly safe. But is it?

There is a difference between d[w] and d[id(w)]. Do you see it?

The answer is that d[w] keeps alive a reference to w, so that w will
never be deallocated while an entry for w appears in d. Not so for
d[id(w)] because id(w) is an int, not a widget.

Let x = d[id(w)]. After w is deallocated, x will not be valid. Of
course, if x is (or contains) any direct reference to w, w will not be
deallocated, but if x only indirectly refers to w, could there be
problems? Well, I suppose not directly, because the GC will keep any
references contained in x alive. Or so I think now :-) But I am a
bit uneasy...

Let us rephrase the question another way. Why doesn't the base
QWidget class do this?::

def __hash__ (self):
return id(self)

Is this safe? If so, why doesn't QWidget do this? If not, exactly
how could it cause problems?

A related question: is there a deep reason why Py2k regards QWidget as
hashable, but Py3k does not?

Your comments, please.

Edward

-- 
You received this message because you are subscribed to the Google Groups 
"leo-editor" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/leo-editor?hl=en.



-- 
You received this message because you are subscribed to the Google Groups 
"leo-editor" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/leo-editor?hl=en.

Reply via email to