From: Terry Jan Reedy Date: Mon, 21 Jun 2021 21:23:29 +0000 (-0400) Subject: bpo-13814: Explain why generators are not context managers (GH-26835) X-Git-Tag: v3.11.0a1~815 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=51f45d085dad3b708f6fe166af517aba69e7e9f7;p=thirdparty%2FPython%2Fcpython.git 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. --- diff --git a/Doc/faq/design.rst b/Doc/faq/design.rst index 68570b33e2f6..720b1e496eb8 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 000000000000..db0c6d6524be --- /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?"