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

Danny Yoo dyoo at hashcollision.org
Fri Sep 19 20:21:13 CEST 2014


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


## Example usage:
class Foo(object):
    def __init__(self, name):
        self.name = name

    def close(self):
        print("closing %s" % self.name)
        self.closed = True


with AutoClosable(Foo('case 1')) as x:
    pass


with AutoClosable(Foo('case 2')) as x:
    raise ValueError, "oops"
#########################################


More information about the Tutor mailing list