[Python-checkins] bpo-13814: Explain why generators are not context managers (GH-26835)

terryjreedy webhook-mailer at python.org
Mon Jun 21 18:02:50 EDT 2021


https://github.com/python/cpython/commit/1e16217204c0e8e595c4d1e869c81899bfe3376b
commit: 1e16217204c0e8e595c4d1e869c81899bfe3376b
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: terryjreedy <tjreedy at udel.edu>
date: 2021-06-21T18:02:43-04:00
summary:

bpo-13814: Explain why generators are not context managers (GH-26835)

Put entry in Design FAQ after a question about a context manager for assignment.
Original patch by Aidan Lowe.
(cherry picked from commit 51f45d085dad3b708f6fe166af517aba69e7e9f7)

Co-authored-by: Terry Jan Reedy <tjreedy at udel.edu>

files:
A Misc/NEWS.d/next/Documentation/2021-06-21-15-46-32.bpo-13814.LDcslu.rst
M Doc/faq/design.rst

diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst
index 68570b33e2f626..720b1e496eb848 100644
--- a/Doc/faq/design.rst
+++ b/Doc/faq/design.rst
@@ -708,6 +708,15 @@ bindings are resolved at run-time in Python, and the second version only needs
 to perform the resolution once.
 
 
+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.
+
+
 Why are colons required for the if/while/def/class statements?
 --------------------------------------------------------------
 
diff --git a/Misc/NEWS.d/next/Documentation/2021-06-21-15-46-32.bpo-13814.LDcslu.rst b/Misc/NEWS.d/next/Documentation/2021-06-21-15-46-32.bpo-13814.LDcslu.rst
new file mode 100644
index 00000000000000..db0c6d6524beeb
--- /dev/null
+++ b/Misc/NEWS.d/next/Documentation/2021-06-21-15-46-32.bpo-13814.LDcslu.rst
@@ -0,0 +1 @@
+In the Design FAQ, answer "Why don't generators support the with statement?"



More information about the Python-checkins mailing list