I was reading that post about cleaning up objects, and I implemented the clever answer from @Chris. I was wondering what were the possibilities of object access at the end, to see how good I could achieve resources handling. The code is the following :
import weakref
import logging
from time import sleep
class A:
def __init__(self):
self.a = "We're good to go !"
self.b = 18
self.formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
class B:
def __init__(self):
self.a = A()
self.b = 56
self._finalizer = weakref.finalize(self, self.close, self.a)
@staticmethod
def close(class_A):
print(class_A.a)
sleep(1)
def amethod(self):
print(self.a.b)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self._finalizer()
b = B()
print(b.b)
b.amethod()
We should expect that output:
56
18
"We're good to go !"
as the string is printed out when B()
is garbage collected. This is what happen in a command line.
But using Spyder, I first get by running this :
56
18
And then, by running the code again:
"We're good to go !"
56
18
So the object isn't garbage collected until the next run. I added the sleep to be sure, thinking that it was maybe a problem of string buffered somehow and not being printed out, but it's clearly the whole block that is not executed. I need to trust Spyder on garbage collection here, is this behaviour documented, and how can I change it ? I'm using spyder 3.3.6 and python 3.8