开发者

Preempting __del__ hmmm

开发者 https://www.devze.com 2022-12-08 02:00 出处:网络
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..

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 readin开发者_开发问答g!!

Steve


__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.


Please use the with statement for this.

See http://docs.python.org/reference/compound_stmts.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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消