Make the @contextmanager of contextlib to be a real contextmanager
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' passBut there is a little bug,when the code block raise a error,the instance cannot run the code which after the keyword 'yield'.So I try to repair this bug, I add a method '_next()' in the Class '_GeneratorContextManager',and then insert it to the the method '__exit__',then we can make the instance like a realcontextmanager.You can cat the concrete content in the attachment. Conmments:the method '_next()' in in line 79,the method '__exit__' in line 97.
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.
participants (2)
-
Moon丶sun
-
Serhiy Storchaka