Search code examples
pythongarbage-collection

how to make sure io module isn't shutdown before garbage collection on close


I have an object with __del__ method. I would like this method be called on interpreter shutdown. The __del__ method would open and write to certain file. It appears io module is shutdown before global garbage collection.

#!/usr/bin/env python3
class Foo:
    def __del__(self):
        with open('/tmp/doge_poop', 'w') as f:
            f.write('corn kernel')
foo=Foo()

Running the above MWE gives the following:

Exception ignored in: <function Foo.__del__ at 0x7f4984176310>
Traceback (most recent call last):
  File "b.py", line 4, in __del__
NameError: name 'open' is not defined

Solution

  • Found a way:

    #!/usr/bin/env python3
    from atexit import register
    class Foo:
        def __del__(self):
            with open('/tmp/doge_poop', 'w') as f:
                f.write('corn kernel')
                print("delete!")
    foo=Foo()
    
    @register
    def _atexit():
        global foo
        del foo
    

    Helped by a member in group https://t.me/py_zh_real .