Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acquiring a regular reference from a weakref proxy in python

Is there a way to get a proper reference for an object for which I get a weakref proxy?

I've gone through the weakref module's documentation and coulnd't get an answer there, or through poking a weakproxy object manually.

like image 887
itai Avatar asked Oct 27 '13 17:10

itai


People also ask

What is __ Weakref __ in Python?

__weakref__ is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of weakref (or sometimes weakproxy ) which is both a weak reference to the object and part of a doubly linked list to all weak references for that object.

What is Weakref proxy?

weakref.proxy(object[,callback])Returns a proxy to the object that uses a weak reference. The returned object has type ProxyType or CallableProxyType, depending on if the object is callable. These objects are not hashable.


1 Answers

Although there's nothing exposed directly on the proxy object itself, it is possible to obtain a reference by abusing the __self__ attribute of bound methods:

obj_ref = proxy.__repr__.__self__

Using __repr__ here is just a random choice, although if you want a generic method it'd be better to use a method that all objects should have.

like image 90
mincrmatt12 Avatar answered Oct 05 '22 01:10

mincrmatt12