bpo-13814: Explain why generators are not context managers (GH-26835) · python/cpython@d881002 (original) (raw)

File tree

2 files changed

lines changed

2 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -709,6 +709,15 @@ bindings are resolved at run-time in Python, and the second version only needs
709 709 to perform the resolution once.
710 710
711 711
712 +Why don't generators support the with statement?
713 +------------------------------------------------
714 +
715 +For technical reasons, a generator used directly as a context manager
716 +would not work correctly. When, as is most common, a generator is used as
717 +an iterator run to completion, no closing is needed. When it is, wrap
718 +it as "contextlib.closing(generator)" in the 'with' statment.
719 +
720 +
712 721 Why are colons required for the if/while/def/class statements?
713 722 --------------------------------------------------------------
714 723
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1 +In the Design FAQ, answer "Why don't generators support the with statement?"