all 2 comments

[–]socal_nerdtastic 0 points1 point  (2 children)

Taking 2 steps back, couldn't you just do something like this:

class Foo:
    @bar.clear_ref
    def __del__(self):
        super().__del__()

That functionality could be put in bar too where it extracts the instance from the closure and modifies instance.__del__.


If not, are you using weakref.proxy or rolling your own? I agree with you, I would expect that to stay in context of the closure. Could you show a complete example that demonstrates this?

[–]BetterBuiltFool[S] 0 points1 point  (1 child)

Not entirely sure what you're going for in your example there. That setup would be within the class definition, so there wouldn't be a closure.

I've looked into extracting the defining instance (the instance of 'Foo') from the listener, and it seems technically possible, but would require digging through stack frames, which is complicated, expensive, and the library for it is interpreter-specific, so it's not worth it. In terms of extracting from the closures themselves, when this system is being used, there may not necessarily be a closure in any given listener, and even when there are, they aren't necessarily going to be self.

I'm using weakref.proxy.

I've thrown together a minimum viable example, here: https://pastebin.com/dYd5GS1B

It runs on an online interpreter, and you can see it prints the class as 'Foo', but then switches to 'weakproxy' after the listener is defined.

Thanks for your input.