views:

28

answers:

1

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?

+1  A: 

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
Matthew Flaschen
i ended up using a decorator. thanks!
Igor