10

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.

itai
  • 1,566
  • 1
  • 12
  • 25

2 Answers2

6

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.

mincrmatt12
  • 382
  • 3
  • 12
-1

I don't know what you mean by a proper reference, but according to: https://pymotw.com/2/weakref/,

you can just use the proxy as if you would use the original object.

import weakref

class ExpensiveObject(object):
    def __init__(self, name):
        self.name = name
    def __del__(self):
        print '(Deleting %s)' % self

obj = ExpensiveObject('My Object')
r = weakref.ref(obj)
p = weakref.proxy(obj)

print 'via obj:', obj.name
print 'via ref:', r().name
print 'via proxy:', p.name
del obj
print 'via proxy:', p.name

This contrasts to using weakref.ref, where you have to call, i.e. use the ()-operator on, the weak reference to get to the original object.

boudewijn21
  • 338
  • 1
  • 9