Logged In: YES
user_id=4771
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.m
ref = 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.
|