On Mon, Mar 16, 2015 at 8:32 AM, Steven D'Aprano
<steve+comp.lang.pyt...@pearwood.info> wrote:
> On Tue, 17 Mar 2015 12:13 am, Marko Rauhamaa wrote:
>
>> If I get an iterator from a black box source, I don't know if I'm
>> allowed/supposed to call close() on it.
>
> In no particular order:
>
> #1
> if hasattr(some_iterator, 'close'):
>     some_iterator.close()
>
>
> #2
> close = getattr(some_iterator, 'close', None)
> if close is not None:
>     close()
>
>
> #3
> try:
>     close = some_iterator.close
> except AttributeError:
>     pass
> else:
>     close()

Note that these fail if some_iterator is a file-like object. Those
have close methods, but as part of the file api, not the iterator api,
and so the owner of the object is probably not expecting you to close
it for them.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to