[Python-Dev] atexit missing an unregister method

Aahz aahz at pythoncraft.com
Tue Apr 26 22:18:30 CEST 2005


On Tue, Apr 26, 2005, Nick Jacobson wrote:
>
> I was looking at the atexit module the other day; it seems like an elegant 
> way to ensure that resources are cleaned up (that the garbage collector 
> doesn't take care of).
> 
> But while you can mark functions to be called with the 'register' method, 
> there's no 'unregister' method to remove them from the stack of functions 
> to be called.  Nor is there any way to view this stack and e.g. call 'del' 
> on a registered function.
> 
> This would be useful in the following scenario, in which x and y are 
> resources that need to be cleaned up, even in the event of a program exit:
> 
> import atexit
> 
> def free_resource(resource):
>    ...
> 
> atexit.register(free_resource, x)
> atexit.register(free_resource, y)

This seems like the wrong way.  Why not do this:

    class ResourceCleanup:
        def register(self, resource, func): ...
        def unregister(self, resource): ...
        def __call__(self): ...

    handler = ResourceCleanup)
    atexit.register(handler)
    handler.register(x, free_resource)
    do(x)
    handler.unregister(x)

Probably further discussion should go to comp.lang.python
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"It's 106 miles to Chicago.  We have a full tank of gas, a half-pack of
cigarettes, it's dark, and we're wearing sunglasses."  "Hit it."


More information about the Python-Dev mailing list