]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-13814: Explain why generators are not context managers (GH-26835)
authorTerry Jan Reedy <tjreedy@udel.edu>
Mon, 21 Jun 2021 21:23:29 +0000 (17:23 -0400)
committerGitHub <noreply@github.com>
Mon, 21 Jun 2021 21:23:29 +0000 (17:23 -0400)
Put entry in Design FAQ after a question about a context manager for assignment.
Original patch by Aidan Lowe.

Doc/faq/design.rst
Misc/NEWS.d/next/Documentation/2021-06-21-15-46-32.bpo-13814.LDcslu.rst [new file with mode: 0644]

index 68570b33e2f6264bf9ef27e7d29540f08d2da90a..720b1e496eb8482ee74b29e99f2bbf6bd5f37854 100644 (file)
@@ -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 (file)
index 0000000..db0c6d6
--- /dev/null
@@ -0,0 +1 @@
+In the Design FAQ, answer "Why don't generators support the with statement?"