import json


def output_generic_result_lazily(out_file, name, retrieve_result):
    """This function is used to output data to file. It doesn't do this straight away
    but instead returns a function which can be called when the data actually should
    be written.

    When the returned function is called a complete JSON-document containing data
    from retrieve_result will be written as one line to the JSON-file.

    :param out_file: file handle to write data to.
    :param name: name to store data under in file.
    :param retrieve_result: function that returns data to write. This should take
                            no arguments and is only called when calling the returned function.
    """

    def output():
        result = retrieve_result()
        data = {
            name: result
        }
        json.dump(data, fp=out_file)
        # Newline to generate JSON Lines data, one doc per line
        out_file.write('\n')

    return output