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
精彩评论