Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a dead weakref in python?

Is there a better way of doing this than:

def create_expired_weakref():
    class Tmp: pass
    ref = weakref.ref(Tmp())
    assert ref() is None
    return ref

Context: I want a default state for my weakref, so that my class can do:

def __init__(self):
    self._ref = create_expired_weakref()

def get_thing(self):
    r = self._ref()  # I need an empty weakref for this to work the first time
    if r is None:
        r = SomethingExpensive()
        self._ref = weakref.ref(r)
    return r
like image 530
Eric Avatar asked Oct 28 '22 06:10

Eric


1 Answers

Another approach is to use duck typing here. If all you care about is that it behaves like a dead weakref with respect to the self._ref() call, then you can do

self._ref = lambda : None

This is what I ended up using when I had a similar desire to have a property that would return a cached value if it was available, but None otherwise. I initialized it with this lambda function. Then the property was

@property
def ref(self):
    return self._ref()

Update: Credit to @Aran-Fey, who I see posted this idea as a comment to the question, rather than as an answer.

like image 60
Mike Jarvis Avatar answered Nov 01 '22 10:11

Mike Jarvis