Design thought for callbacks
Fabio Zadrozny
fabiofz at gmail.com
Tue Feb 24 08:23:13 EST 2015
Hi Cem,
I didn't read the whole long thread, but I thought I'd point you to what
I'm using in PyVmMonitor (http://www.pyvmmonitor.com/) -- which may already
cover your use-case.
Take a look at the callback.py at
https://github.com/fabioz/pyvmmonitor-core/blob/master/pyvmmonitor_core/callback.py
And its related test (where you can see how to use it):
https://github.com/fabioz/pyvmmonitor-core/blob/master/_pyvmmonitor_core_tests/test_callback.py
(note that it falls back to a strong reference on simple functions -- i.e.:
usually top-level methods or methods created inside a scope -- but
otherwise uses weak references).
Best Regards,
Fabio
On Sat, Feb 21, 2015 at 12:44 AM, Cem Karan <cfkaran2 at gmail.com> wrote:
> Hi all, I'm working on a project that will involve the use of callbacks,
> and I want to bounce an idea I had off of everyone to make sure I'm not
> developing a bad idea. Note that this is for python 3.4 code; I don't need
> to worry about any version of python earlier than that.
>
> In order to inform users that certain bits of state have changed, I
> require them to register a callback with my code. The problem is that when
> I store these callbacks, it naturally creates a strong reference to the
> objects, which means that if they are deleted without unregistering
> themselves first, my code will keep the callbacks alive. Since this could
> lead to really weird and nasty situations, I would like to store all the
> callbacks in a WeakSet (
> https://docs.python.org/3/library/weakref.html#weakref.WeakSet). That
> way, my code isn't the reason why the objects are kept alive, and if they
> are no longer alive, they are automatically removed from the WeakSet,
> preventing me from accidentally calling them when they are dead. My
> question is simple; is this a good design? If not, why not? Are there any
> potential 'gotchas' I should be worried about?
>
> Thanks,
> Cem Karan
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150224/6bf222f1/attachment.html>
More information about the Python-list
mailing list