python:闭包和类

Jas*_*n S 6 python class atexit

我需要注册一个atexit用于类的函数(请参见Foo下面的示例),不幸的是,我没有通过方法调用进行清理的直接方法:其他代码,我无法控制,调用Foo.start()Foo.end()但是Foo.end()如果遇到错误,有时不会调用,因此我需要清理自己。

在这种情况下,我可以使用一些关于闭包的建议:

class Foo:
  def cleanup(self):
     # do something here
  def start(self):
     def do_cleanup():
        self.cleanup()
     atexit.register(do_cleanup)
  def end(self):
     # cleanup is no longer necessary... how do we unregister?
Run Code Online (Sandbox Code Playgroud)
  • 闭包是否正常工作,例如在 中do_cleanup,自绑定的值是否正确?

  • 如何取消注册 atexit() 例程?

  • 有一个更好的方法吗?

编辑:这是 Python 2.6.5

Ros*_*ron 6

使注册表成为全局注册表和调用其中函数的函数,并在必要时从那里删除它们。

cleaners = set()

def _call_cleaners():
    for cleaner in list(cleaners):
        cleaner()

atexit.register(_call_cleaners)

class Foo(object):
  def cleanup(self):
     if self.cleaned:
         raise RuntimeError("ALREADY CLEANED")
     self.cleaned = True
  def start(self):
     self.cleaned = False
     cleaners.add(self.cleanup)
  def end(self):
     self.cleanup()
     cleaners.remove(self.cleanup)
Run Code Online (Sandbox Code Playgroud)