Python: dereferencing weakproxy
python, weak-references
Solution
I know this is an old question but I was looking for an answer recently and came up with something. Like others said, there is no documented way to do it and looking at the implementation of weakproxy type confirms that there is no standard way to achieve this.
My solution uses the fact that all Python objects have a set of standard methods (like __repr__) and that bound method objects contain a reference to the instance (in __self__ attribute).
Therefore, by dereferencing the proxy to get the method object, we can get a strong reference to the proxied object from the method object.
Example:
>>> def func():
... pass
...
>>> weakfunc = weakref.proxy(func)
>>> f = weakfunc.__repr__.__self__
>>> f is func
True
Another nice thing is that it will work for strong references as well:
>>> func.__repr__.__self__ is func
True
So there's no need for type checks if either a proxy or a strong reference could be expected.
Edit:
I just noticed that this doesn't work for proxies of classes. This is not universal then.
Problem
Is there any way to get the original object from a weakproxy pointed to it? eg is there the inverse to `weakref.proxy()`? A simplified example(python2.7): ``` import weakref class C(object): def __init__(self, other): self.other = weakref.proxy(other) class Other(object): pass others = [Other() for i in xrange(3)] my_list = [C(others[i % len(others)]) for i in xrange(10)] ``` I need to get the list of unique `other` members from `my_list`. The way I prefer for such tasks is to use `set`: ``` unique_others = {x.other for x in my_list} ``` Unfortunately this throws `TypeError: unhashable type: 'weakproxy'` I have managed to solve the specific problem in an imperative way(slow and dirty): ``` unique_others = [] for x in my_list: if x.other in unique_others: continue unique_others.append(x.other) ``` but the general problem noted in the caption is still active. What if I have only `my_list` under control and `others` are burried in some lib and someone may delete them at any time, and I want to prevent the deletion by collecting nonweak refs in a list? Or I may want to get the `repr()` of the object itself, not `<weakproxy at xx to Other at xx>` I guess there should be something like `weakref.unproxy` I'm not aware about.