在python中引发异常后的可变版本

问题描述 投票:0回答:1

我有一些如下代码:

class A:
    def __del__(self):
        print('del A')


class B:
    def foo(self):
        a = A()
        raise RuntimeError


b = B()
try:
    b.foo()
    print('after b.foo() 1')
except RuntimeError:
    print('catch error')

print('after b.foo() 2')

输出为:

catch error
del A
after b.foo() 2

我的问题是:

1]似乎在处理异常后删除了a。在这种情况下,任何人都可以帮助解释变量发布的顺序吗?

2)如何在a块的开头手动释放变量except RuntimeError

关于用例的更多话:

我想捕获B.foo()中出现的CUDA内存不足错误,并在a块的开头释放一些except RuntimeError(某些变量占用太多的CUDA内存)。然后,我可以将数据拆分为较小的部分,然后再次进行。

python python-3.x error-handling except
1个回答
0
投票

a实例的属性设置并删除它:

B

如果使用class B: def foo(self, num): self.a = A() # make it an attribute so you can access it from outside if num > 20: raise RuntimeError b = B() try: b.foo(42) print('after b.foo() 1') except RuntimeError: del b.a # now you can explicitly delete it print('catch error') b.foo(18) print('after b.foo() 1a') print('after b.foo() 2') 可能更清洁,然后对其进行迭代直到为true,然后继续。

不确定上述方法是否适用于CUDA。


0
投票

我想我找到了解决方案。 [test_memory(self, data)](traceback.clear_frames)发挥了魔力。

https://docs.python.org/3/library/traceback.html#traceback.clear_frames
© www.soinside.com 2019 - 2024. All rights reserved.