I would like to access each generated object separately, without having the need to iterate directly over the generator function.
I have the following "generator" function which figures out whether I should download a file or return it as a file object
def retrieve_file(content, to_download, filename):
if to_download:
# Should download this file to the local computer
with open(filename, 'wb') as f:
f.write(content)
return filename
else:
# Do not download, keep it as a file object
output = StringIO()
output.write(content)
return output # Should be replaced with yield?
The following function which actually downloads the files and calls the previous function
def get_all_files(to_download):
for year in [2000, 2001, 20002, 2003]:
content = download_file(year)
result = retrieve_file(content,
to_download,
'file-%s.pdf' % year)
return result
And the main function which in this case downloads all files as objects and then parses each one separately
def main():
for file in get_all_files(True):
parse_file(file)
In this example, having get_all_files function removed, and replacing the second return in retrieve_file with yield, would work. The problem is that I would like to separate the 2 functions (main and get_all_files) because they are in two different modules
get_all_files
? What are you doing withresult
?to_download
inretrieve_file
is confusing, because you aren't actually downloading anything in that function.