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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.