i'm having a difficult time understanding what the second 'with open' function does here.
so, in the first 'with open' part, we've essentially said
out = open(save_as_file, 'wb+')
fp = open(save_as_file, 'r')
def load_from_url(self, url, save_as_file=None):
fp = requests.get(url, stream=True,
if save_as_file is None:
with open(save_as_file, 'wb+') as out:
buffer = fp.read(81920)
if not buffer:
with open(save_as_file) as fp:
You are correct that the second
with statement opens the file for reading.
What happens is this:
load_from_fileon the response and return the result
load_from_fileon the contents of the file and return the result
So essentialy, if
save_as_file is set it stores the response body in a file, processes it and then returns the processed result. Otherwise it just processes the response body and returns the result.
The way it is implemented here is likely because
load_from_file expects a file-like object and the easiest way the programmer saw of obtaining that was to read the file back.
It could be done by keeping the response body in memory and using Python 3's io module or Python 2's StringIO to provide a file-like object that uses the response body from memory, thereby avoiding the need to read the file again.
fp is reassigned in the second
with statement in the same way as any other variable would be if you assigned it another value.