I would like to suggest you use Python with statements for operating the resources that need to be cleaned up. To use that statement, create a class with the following methods:
def __enter__(self)
def __exit__(self, exc_type, exc_value, traceback)
In your example above, you'd use
class Package:
def __init__(self):
self.files = []
def __enter__(self):
return self
# ...
def __exit__(self, exc_type, exc_value, traceback):
for file in self.files:
os.unlink(file)
If somebody wants to use your package, they can write this:
with Package() as package_obj:
# use package_obj
The package_obj will act as an instance of type Package. The __exit__ function will be called, regardless of whether or not an exception occurs.
The above code is having a package that is using its constructor without using the with clause in Python. If you do not want this then you can create a PackageResource class that defines the __enter__ and __exit__ methods. Then, the Package class would be defined inside the __enter__ method and returned. That way, the caller never could instantiate the Package class without using a with the statement:
class PackageResource:
def __enter__(self):
class Package:
...
self.package_obj = Package()
return self.package_obj
def __exit__(self, exc_type, exc_value, traceback):
self.package_obj.cleanup()
#You'd use this as follows:
with PackageResource() as package_obj:
# use package_obj