0

If it is so, please do not hesitate to close question as duplicate. :)

In my code, I have a lot of blocks that look like

try:
    load_from_disk(pathtofile)
except IOError:
    datapiece = comp_this_data( **dictofargs )
    save_to_disk(pathtofile, datapiece)

Question: How to define a routine that takes care of possible precomputed data for different comp_this_data?

Maybe, this is an easy case for python decorators. However, as I understood, the decorator is part of the function definition, which I don't want to change.

Any ideas?

Jan
  • 4,932
  • 1
  • 26
  • 30

1 Answers1

0

Here is an example of how you can wrap multiple computation functions:

def compute_and_save(compute_f, file, *args, **kwargs):
    try:
        load_from_disk(file)
    except IOError:
        datapiece = compute_f(*args, **kwargs)
        save_to_disk(file, datapiece)

if __name__ == "__main__":
    compute_and_save(comp_this_data, file, **dictofargs)
    compute_and_save(comp_this_data_2, file, **dictofargs)
Sunny Nanda
  • 2,362
  • 1
  • 16
  • 10
  • How does this answer "[take] care of possible precomputed data for different `comp_this_data`"? – jonrsharpe Feb 11 '14 at 09:18
  • Well, it does in so far as you can pass different `comp_this_data` to it. – Jan Feb 11 '14 at 09:19
  • From OP's code, it looks like the computed data is stored in a file. If the file is not present (i.e. we get IOError), we assume that it needs to be computed again. – Sunny Nanda Feb 11 '14 at 09:20