This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author terry.reedy
Recipients Guido.van.Rossum, gvanrossum, miss-islington, serhiy.storchaka, terry.reedy
Date 2021-06-26.14:54:06
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1624719246.88.0.362546807715.issue44482@roundup.psfhosted.org>
In-reply-to
Content
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.
History
Date User Action Args
2021-06-26 14:54:06terry.reedysetrecipients: + terry.reedy, gvanrossum, serhiy.storchaka, Guido.van.Rossum, miss-islington
2021-06-26 14:54:06terry.reedysetmessageid: <1624719246.88.0.362546807715.issue44482@roundup.psfhosted.org>
2021-06-26 14:54:06terry.reedylinkissue44482 messages
2021-06-26 14:54:06terry.reedycreate