Qcodes icon indicating copy to clipboard operation
Qcodes copied to clipboard

feature: replace __del__ with weakref.finalize()

Open maximilianluc opened this issue 3 years ago • 3 comments

Feature addition: replacing del with weakref.finalize() as called method during object garbage collection.

Issue: #3774

  • renamed __del__ as __finalize, logic stays the same.
  • added weakref.finalize() in __init__ in instrument.py calling upon '__finalize()' during gc.

maximilianluc avatar Jul 12 '22 14:07 maximilianluc

I think we can rename __del__ to __finalize to be called as weakref.finalize(obj, __finalize), right? With the logic in __del__ , now in __finalize(), the close() method should stay alive until the instrument is gc'd. Or am I overlooking something?

maximilianluc avatar Jul 12 '22 14:07 maximilianluc

Codecov Report

Merging #4386 (a450af6) into master (a450af6) will not change coverage. The diff coverage is n/a.

:exclamation: Current head a450af6 differs from pull request most recent head 49d7082. Consider uploading reports for the commit 49d7082 to get more accurate results

@@           Coverage Diff           @@
##           master    #4386   +/-   ##
=======================================
  Coverage   68.09%   68.09%           
=======================================
  Files         299      299           
  Lines       31535    31535           
=======================================
  Hits        21473    21473           
  Misses      10062    10062           

codecov[bot] avatar Jul 12 '22 14:07 codecov[bot]

@maximilianluc Thanks for this. It looks great but I will need a little bit of time to test this manually to see how it works in practice

jenshnielsen avatar Jul 25 '22 14:07 jenshnielsen

@maximilianluc Sorry for the late response. I have spent a bit of time investigating this and unfortunately its a bit more complicated as the finalize method cannot contain a reference to self since that would increase the ref count to the instrument preventing the finalizer to be called. https://docs.python.org/3/library/weakref.html#weakref.finalize

In https://github.com/QCoDeS/Qcodes/pull/5341 I have implemented a partial solution for visa instruments that do not have this issue

jenshnielsen avatar Sep 03 '23 18:09 jenshnielsen