1

I'm re-writing an analysis application that calculates dozens of factors that are later used in a statistical model. Currently, the application is structured where the various factors are calculated as such...

factor1 = calculate_factor1()
factor2 = calculate_factor2()
factor3 = calculate_factor3()

...and so on.

But what if the function calculate_factor2() is updated? Because the factors are stored in a database, every other factor does not need to be re-calculated every time the program runs. Or, as another example, we might add factor67 and do not need to calculate the rest.

Right now, we are currently commenting out the lines of factors we don't need to calculate. There has to be a better way?

TravisVOX
  • 20,342
  • 13
  • 37
  • 41
  • 1
    Use `sys.argv` to get input arguments to your script and bunch of `if` statements to run your code conditionally based on those input arguments? – Łukasz Rogalski Mar 30 '17 at 11:08
  • I was hoping/thinking there was a way to avoid a bunch of if statements... – TravisVOX Mar 30 '17 at 11:26
  • you can store your functions in dict like `calculate_factors_funcs = {1: calculate_factor1, 2: calculate_factor2, ...}`. After that you do `for factor_id in factors_to_compute: calculate_factors_funcs[factor_id]()`. In this way you can avoid writing lots of if statements. Obviously you need to create `factors_to_compute` based on user input. – Łukasz Rogalski Mar 30 '17 at 11:35

1 Answers1

0

Without knowing how each function is structured, you can simply create another python script which calls the functions you have created. I mean - in one doc:

def calculate_factor_1()

def calculate factor_2()
   ....

In another

factor = calculate_factor_1()

This way you need only call the calculation functions individually when you need them. You could also make them callable from the command line so you only call the functions you need as and when.

Python: Run function from the command line like this :)

Community
  • 1
  • 1
JP1
  • 731
  • 1
  • 10
  • 27
  • This is sort of the approach I've thought made the most sense in thinking it through... creating a second script that only calculates the factors needed alongside the original which calculates all of them. – TravisVOX Mar 30 '17 at 11:29
  • and shouldnt take too much work to get from where you are now :) – JP1 Mar 30 '17 at 11:45