bpo-13814: Explain why generators are not context managers (GH-26835) · python/cpython@51f45d0 (original) (raw)
File tree
2 files changed
lines changed
- Misc/NEWS.d/next/Documentation
2 files changed
lines changed
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -708,6 +708,15 @@ bindings are resolved at run-time in Python, and the second version only needs | ||
708 | 708 | to perform the resolution once. |
709 | 709 | |
710 | 710 | |
711 | +Why don't generators support the with statement? | |
712 | +------------------------------------------------ | |
713 | + | |
714 | +For technical reasons, a generator used directly as a context manager | |
715 | +would not work correctly. When, as is most common, a generator is used as | |
716 | +an iterator run to completion, no closing is needed. When it is, wrap | |
717 | +it as "contextlib.closing(generator)" in the 'with' statment. | |
718 | + | |
719 | + | |
711 | 720 | Why are colons required for the if/while/def/class statements? |
712 | 721 | -------------------------------------------------------------- |
713 | 722 |
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?" |