[Tutor] Using 'requests' + 'with statement' in Python 3.4.1

Peter Otten __peter__ at web.de
Fri Sep 19 20:30:29 CEST 2014


Danny Yoo wrote:

> I should have added that you can write your own context manager for
> requests; it shouldn't be too bad.  I'd expect the helper code to be
> something like:

> class AutoClosable(object):
>     def __init__(self, closable):
>         self.closable = closable
> 
>     def __enter__(self):
>         return self.closable
> 
>     def __exit__(self, type, value, traceback):
>         self.closable.close()
>         ## reraise exception if one occurred:
>         return False

There is also

<https://docs.python.org/dev/library/contextlib.html#contextlib.closing>




More information about the Tutor mailing list