Search code examples
pythonappearance

How can I generate some Python scripts based on different conditions nicely?


I want to generate some Python scripts based on different conditions. It means: I have a constant body of my Python scripts, which is exactly the same in all the different conditions, but due to the fact that I have several different conditions, there are some regions in those Python scripts that should be changed. Let's say this is my constant part, which is similar for all the conditions:

import numpy as np

variables = []

for i in range(100):
 variables.append(tempVariable)

print variables

And I have 4 different conditions, where tempVariable is calculated differently as:

Condition 1: tempVariable = i

Condition 2: tempVariable = i**2

Condition 3: tempVariable = i**3

Condition 4: tempVariable = i + 4.34

Note that I don't want to use if statement to switch over these four conditions cause these conditions are in fact different cases and are not related together. At the end, I want to have variables for these four different conditions and cases independently. My idea is that to put these four cases or conditions into a txt file and treat the constant part of the Python script as an another txt file and iterate over all these four conditions or cases and add the necessary part for calculating the tempVariable before appending it into variables. Of course, it looks pretty ugly and more importantly I want to ship it to other people to be able to use it. I appreciate if there is any more nice and generic approach to it. In my real application, I have 94 different conditions or cases, which would be really ugly, if I want to put them under some if or elif statements. Any suggestion or idea is appreciated.


Solution

  • Finally, I found a solution, which is really better fit for cases that there are countless conditions (i.e. 1000 different conditions). In fact, I put all the commands in a text file that could be parsed and read automatically as:

    commands.txt:

    tempVariable = i
    tempVariable = i**2
    tempVariable = i**3
    tempVariable = i + 4.34
    

    Then, I read and execute them like this:

    def Execute(command):
     variables = []
    
     for i in range(100):
      exec(command)
      variables.append(tempVariable)
    
     print variables
    
    if __name__ == "__main__":
     conditions = open('commands.txt').read().split('\n')[:-1]
     map(Execute, conditions)