This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author sjdrake
Recipients docs@python, martin.panter, mpaolini, pitrou, r.david.murray, sjdrake
Date 2015-04-24.05:17:32
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1429852653.38.0.0355970967883.issue23227@psf.upfronthosting.co.za>
In-reply-to
Content
Ok, I can accept that.  I think my mistake was to assume that because a generator has a close() method, I could treat it as a lightweight wrapper for another closeable object.

But it's better to regard a generator function that wraps an iterable as something more akin to map() or filter(), and use a class if it's necessary to wrap a file such that close() is passed through.

I happened to take a fresh look at this just the other day and it also occurred to me that the kind of composition I was trying to do can work if it's generators all the way down:

def open_lines(name, mode='rt', buffering=-1):
    with open(name, mode, buffering) as f:
        for line in f:
            yield line

def logged_lines(f):
    try:
        for line in f:
            logging.warning(line.strip())
            yield line
    finally:
        f.close()

lines = open_lines('yyy', 'r')
if verbose:
    lines = logged_lines(lines)
try:
    for line in lines:
        print(line)
finally:
    lines.close()

So a generator can transparently wrap a plain iterable or another generator, but not closeable objects in general.  There's nothing really wrong with that, so I'm happy for this issue to be closed as invalid.
History
Date User Action Args
2015-04-24 05:17:33sjdrakesetrecipients: + sjdrake, pitrou, r.david.murray, docs@python, martin.panter, mpaolini
2015-04-24 05:17:33sjdrakesetmessageid: <1429852653.38.0.0355970967883.issue23227@psf.upfronthosting.co.za>
2015-04-24 05:17:33sjdrakelinkissue23227 messages
2015-04-24 05:17:32sjdrakecreate