[docs] [issue13814] Document why generators don't support the context management protocol

Nick Coghlan report at bugs.python.org
Sun Jan 22 07:58:17 CET 2012


Nick Coghlan <ncoghlan at gmail.com> added the comment:

Generators deliberately don't support the context management protocol. This is so that they raise an explicit TypeError or AttributeError (pointing out that __exit__ is missing) if you leave out the @contextmanager decorator when you're using a generator to write an actual context manager.

Generators supporting the context management protocol natively would turn that into a far more subtle (and confusing) error: your code would silently fail to invoke the generator body.

Ensuring this common error remains easy to detect is far more important than making it easier to invoke close() on a generator object (particularly when contextlib.closing() already makes that very easy).

----------
assignee:  -> docs at python
components: +Documentation
nosy: +docs at python
stage: test needed -> needs patch
status: pending -> open
title: Generators as context managers. -> Document why generators don't support the context management protocol

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue13814>
_______________________________________


More information about the docs mailing list