You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
According to the documentation of the weakref module,
weakreferences can be applied to
"...class instances, functions written in Python (but
not in C), methods (both bound and unbound)..."
In reality, bound methods cannot be referenced (see bug
813299):
importweakref## this works:deftestF( event ): passr=weakref.ref( testF )
## this doesnt:classEventListener:
defhandleEventA( self, event ):
passt=EventListener()
## gives a "dead" refr=weakref.ref( t.handleEventA )
This behaviour is unexpected for anyone not aquainted
to the inner clockwork of python and unfortunate
because it, for example, prevents to keep weak
references to callback methods in event handling
patterns.
Of course, the weakref documentation is ultimately right,
and the problem, unrelated to bound methods, is that you
always get a dead weakref if you do
weakref.ref(<expr-than-returns-a-new-object>)
But I'm not being particularly helpful here.
A trick simpler than the cookbook proposals is to force the
method object to be alive as long as the instance itself by
storing it on the instance:
obj=MyClass()
obj.m=obj.mref=weakref.ref(obj.m)
This works because the last "obj.m" returns an existing
object, as opposed to one created just-in-time. This
might be mentioned in the weakref documentation with the
comment that it's a general rule to be careful not to take
weakrefs to short-lived object; the same problem would
occur e.g. when taking a weakref to "obj.a" where "a" is
a computed property. Storing the result back on "obj" --
under the same or another name -- is a workaround.
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: