tags:

views:

78

answers:

3

Hi SO's

I need to preempt __del__ and I want to know what is the right way to do this. Basically my question in code is this..

class A:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("In init")
        self.closed = False

    def close(self):
        self.log.debug("Doing some magic")
        self.closed = True

    def __del__(self):
        if not self.closed:
            self.close()
        self.log.debug("In closing")

        # What should go here to properly do GC??

Is there any way to now call the standard GC features?

Thanks for reading!!

Steve

+4  A: 

__del__ isn't a true destructor. It is called before an object is destroyed to free any resources it is holding. It need not worry about freeing memory itself.

You can always call the parent class' __del__, too, if you are inheriting a class which may also have open resources.

Jeff Ober
+1  A: 

If you're looking to call the GC manually then call gc.collect().

Nathan Z
+3  A: 

Please use the with statement for this.

See http://docs.python.org/reference/compound%5Fstmts.html#the-with-statement

The with statement guarantees that if the enter() method returns without an error, then exit() will always be called.

Rather than fool around with __del__, use __exit__ of a context manager object.

S.Lott
Could you be a bit more specific -- thanks!
rh0dium
@rh0dium: Did you read about the with statement and the context manager? What questions did you have?
S.Lott
Only use the with statement if you know your code will not be used with versions of Python prior to 2.5, when it was introduced.
Jeff Ober