-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Document why generators don't support the context management protocol #58022
Comments
Generators should support the with statement with __exit__ calling self.close(). with genfunc() as g:
for item in g:
print(item) |
If you want to call .close() automatically on something you can use contextlib.closing(): http://docs.python.org/library/contextlib.html#contextlib.closing |
Calling g.close() is pointless for a generator used in normal pull mode and run to completion, as in the example. The generator is already 'closed', so g.close() does not do anything useful. See The method was added to be used with .send() so that generators used in push mode could be told to finish up when there is nothing more to send. For such rare uses, contextlib.closing should usually be sufficient, I think. So I think this issue should be closed. |
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). |
Looks like the right approach, I hadn't thought of the design FAQ, but it makes sense as a place to put it. I made a couple of review comments. |
I added a simplified answer after a similar question about assignment and CMs. |
Note: Rietveld patch reviews are no longer accessible so I could not look at R. David's comments. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: