1

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

4
  • Is that the entirety of get_all_files? What are you doing with result? Commented Jan 19, 2019 at 0:14
  • Until now I have not returned it because I used to call it with to_download=False. edited
    – toothpick
    Commented Jan 19, 2019 at 0:19
  • FYI, the variable to_download in retrieve_file is confusing, because you aren't actually downloading anything in that function. Commented Jan 19, 2019 at 0:27
  • That's true, I will take that into account :)
    – toothpick
    Commented Jan 19, 2019 at 0:30

1 Answer 1

0

Just replace return in your get_all_files with yield. This will allow you to iterate over each file.

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)
        yield result
2
  • How about the option if to_download=False?
    – toothpick
    Commented Jan 19, 2019 at 0:29
  • Why would that matter? In both cases you return an object that is returned. It will behave the same way. Commented Jan 19, 2019 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.