Python __del__ 未在异常时调用

Dan*_*Dan 8 python destructor exception

我试图将一个写得不好的 Python 模块(我无法控制)包装在一个类中。问题是,如果我没有显式调用该模块的 close 函数,那么 python 进程会在退出时挂起,因此我尝试使用具有del方法的类来包装该模块,但是del方法似乎并不适用呼吁例外。

例子:

class Test(object):
    def __init__(self):
        # Initialize the problematic module here
        print "Initializing"

    def __del__(self):
        # Close the problematic module here
        print "Closing"

t = Test()
# This raises an exception
moo()
Run Code Online (Sandbox Code Playgroud)

在这种情况下,不会调用del并且 python 挂起。我需要以某种方式强制Python在对象超出范围时立即调用del (就像C++那样)。请注意,我无法控制有问题的模块(即无法修复首先导致此问题的错误),也无法控制使用包装器类的人(不能强迫他们使用“with”,所以我可以'也不使用退出)。

有没有什么好的方法可以解决这个问题?

谢谢!

小智 5

如果您希望在异常时释放某些资源,请考虑 __enter__ + __exit__ 范例。

class Test(object):
    def __enter__(self):
        pass

    def __exit__(self):
        pass  # Release your resources here

with Test() as t:
    moo()
Run Code Online (Sandbox Code Playgroud)

当执行进入'with'块时,调用't'的方法__enter__(),然后由于正常流程或异常而离开块,调用't'的方法__exit__() 。

  • `__exit__` 具有更长的签名,而不仅仅是 `self` (3认同)