What are the implications of registering an instance method with atexit in Python?

Suppose I have a really large Python class that can consume enough memory. The class has some method that is responsible for clearing some things when the interpreter exits and it registers with the atexit module:

import atexit
import os

class ReallyBigClass(object):
    def __init__(self, cache_file):
        self.cache_file = open(cache_file)
        self.data = <some large chunk of data>
        atexit.register(self.cleanup)

    <insert other methods for manipulating self.data>

    def cleanup(self):
        os.remove(self.cache_file)

Different instances of this class can come and go throughout the life of the program. My questions:

atexit, , , del, ? , atexit.register() , ? , , atexit, ? , , ?

+5
2

atexit , . , , atexit . . ,

import atexit
import os
import gc
import random

class BigClass1(object):
    """atexit function tied to instance method"""
    def __init__(self, cache_filename):
        self.cache_filename = cache_filename
        self.cache_file = open(cache_filename, 'wb')
        self.data = [random.random() for i in range(10000000)]
        atexit.register(self.cleanup)

    def cleanup(self):
        self.cache_file.close()
        os.remove(self.cache_filename)

class BigClass2(object):
    def __init__(self, cache_filename):
        """atexit function decoupled from instance"""
        self.cache_filename = cache_filename
        cache_file = open(cache_filename, 'wb')
        self.cache_file = cache_file
        self.data = [random.random() for i in range(10000000)]

        def cleanup():
            cache_file.close()
            os.remove(cache_filename)

        atexit.register(cleanup)

if __name__ == "__main__":
    import pdb; pdb.set_trace()

    big_data1 = BigClass1('cache_file1')
    del big_data1
    gc.collect()

    big_data2 = BigClass2('cache_file2')
    del big_data2
    gc.collect()

, , big_data1, , , big_data2 , del. ( ).

+7

atexit :

try:
    # Your whole program
finally:
    if sys.exitfunc:
        sys.exitfunc()

module atexit sys.exitfunc . - - - , .

1: , , sys.exitfunc sys.exit(EXIT_CODE), "EXIT_CODE"

2: atexit , sys.exit( SystemExit)

0

All Articles