开发者

making a python object unsable after a finalize-type call

I have a python object which wraps a sensitive and important resource on the system. I have a cleanup() function which safely releases various locks used by the object.

I 开发者_如何转开发want to make sure that after a call to cleanup() the object becomes unusable. Ideally, any call to any member function of the object would raises an exception. Is there a way to do this that does not involve checking a flag in every function?


One way is to simply set all the instance variables to None. Then, doing pretty much anything will cause AttributeError or TypeError. A more sophisticated approach is to wrap instance methods with a decorator. The decorator can check if the close has been disposed. If so, it throws an exception:

class Unusable:
    def __init__(self):
        self.alive = True

    def notcleanedup(func):
        def operation(self, *args, **kwargs):
            if self.alive:
                func(self, *args, **kwargs)
            else:
                raise Exception("Use after cleanup")

        return operation

    @notcleanedup
    def sensitive(self, a, b):
        print a, b

    def cleanup(self):
        self.alive = False
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜