[Python-ideas] Make the @contextmanager of contextlib to be a real contextmanager
Serhiy Storchaka
storchaka at gmail.com
Sat Jan 5 09:45:34 EST 2019
05.01.19 14:52, Moon丶sun пише:
> As we know,when we import the module--'contextlib',we can use the
> decorator '@contextmanager' and keyword ‘yield’ to make a 'instance' of
> Class '_GeneratorContextManager' in 'contextlib' module,then we can use
> it like:
> with 'instance' as 'xx':
> 'code block'
> pass
> But there is a little bug,when the code block raise a error,the instance
> cannot run the code which after the keyword 'yield'.
This is not a bug.
Consider the following example:
@contextmanager
def cm():
try:
yield
except BaseException as err:
print('Fail:', err)
raise
else:
print('Success')
with cm():
1/0
What result would you expect? Test it with the stdlib implementation and
with your implementation.
More information about the Python-ideas
mailing list