walac/pyusb — pull request #78 by dywisor (2014-11-27 06:09:56+00:00)
Title: Finalize objects before exiting

This should fix issue #66:

> Starting with (C)Python 3.4, the GC features "Safe object finalization" [0],
> which doesn't work nicely with pyusb's object structure.
>
> Required globals / modules may already have been deleted (set to None)
> when an object's __del__() method gets called [1], which
> randomly breaks libusb calls etc. when calling sys.exit().
>
> Use the atexit module to solve this (indirectly via weakref.finalize()).
>
> This commit adds a class that takes care of object finalization.
> Classes/objects can adopt this functionality by inheriting
> AutoFinalizedObject and renaming their __del__() method to _finalize_object().
>
> Shouldn't break existing use cases, but adds a few layers of indirection.
> A __del__() call gets processed as follows:
>
> __del__() -> finalize() -> [...]
> -> _do_finalize_object() -> _finalize_object()
>
> All methods in this call chain are provided by AutoFinalizedObject,
> derived classes should override the no-op _finalize_object() method.
>
> The "[...]" part depends on the python version:
> * < 3.4:
> * >= 3.4: _finalizer() -> _do_finalize_object_ref()
>

Needs testing, esp. with Python < 2.7.

The ``FIXME DBGPRINT`` lines should be removed when merging ;)