Created by: zhiqiu
Paddle uses contextlib.contextmanager
internally to decorated several context managers. For example, a simple looks like:
var = 0
@contextlib.contextmanager
def guard(tracer):
var = 1
yield
var = 0
with guard():
# do something
# raise exception
Normally, when entering the with
context, the code block before yield in function guard()
is executed and var
is set to 1; and when exiting the context, the code block after yield in function guard() is executed and var
is set to 0.
However, when exception raised inside with
context, the code block after yield in function guard() is cannot be executed and var
cannot set back to 0. This may cause some errors and problems.
One typical problem is in unittest
, if one unittest
that using context manager failed, the others will continues to be executed, with the wrong context.
This PR add try...finally...
to exit the context manager safely, and solve the problems discussed above.