generator/coroutine terminology

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Mar 16 10:32:10 EDT 2015


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()


#4 (The most pythonic solution of all.) 
If you want to call close(), for some reason, *make it part of your API* and
insist that whatever object is passed to you supports close(), or else it
is an error.




-- 
Steven




More information about the Python-list mailing list