Message396553
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. |
|
Date |
User |
Action |
Args |
2021-06-26 14:54:06 | terry.reedy | set | recipients:
+ terry.reedy, gvanrossum, serhiy.storchaka, Guido.van.Rossum, miss-islington |
2021-06-26 14:54:06 | terry.reedy | set | messageid: <1624719246.88.0.362546807715.issue44482@roundup.psfhosted.org> |
2021-06-26 14:54:06 | terry.reedy | link | issue44482 messages |
2021-06-26 14:54:06 | terry.reedy | create | |
|