Terry J. Reedy <tjre...@udel.edu> added the comment:

Nick Coughlin explained on issue 13814 msg151763 why he thought that making 
generators be context managers could/should not be done.

"Generators deliberately don't support the context management protocol. This is 
so that they raise an explicit TypeError or AttributeError (pointing out that 
__exit__ is missing) if you leave out the @contextmanager decorator when you're 
using a generator to write an actual context manager.

Generators supporting the context management protocol natively would turn that 
into a far more subtle (and confusing) error: your code would silently fail to 
invoke the generator body.

Ensuring this common error remains easy to detect is far more important than 
making it easier to invoke close() on a generator object (particularly when 
contextlib.closing() already makes that very easy)."

The new entry in the Design FAQ is this:

"Why don’t generators support the with statement?

For technical reasons, a generator used directly as a context manager would not 
work correctly. When, as is most common, a generator is used as an iterator run 
to completion, no closing is needed. When it is, wrap it as 
“contextlib.closing(generator)” in the ‘with’ statment."

If Nick's explanation is not currently correct, the above should be removed.  
If it is, perhaps further doc is needed.

----------
nosy: +terry.reedy

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44482>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to