'NoneType' in contextmanager prevent proper RuntimeError to be raised

MRAB python at mrabarnett.plus.com
Wed May 20 19:44:12 EDT 2015


On 2015-05-21 00:20, Daniel Gonçalves wrote:
> When you decorate a function with contextmanager that didn't yield you got an AttributeError instead of a proper RuntimeError "generator didn't yield". For example:
>
>>>> @contextlib.contextmanager
>>>> def foo():
> ...     pass
> ...
>>>> with foo():
> ...     do_something()
> ...
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
>      return self.gen.next()
> AttributeError: 'NoneType' object has no attribute 'next'
>
> The proper exception should be a RuntimerError with the "generator didn't yield" message. At least for Python version 2.7.6.
>
If it doesn't contain a 'yield', it's not a generator, it's a function.




More information about the Python-list mailing list