KubiK888
KubiK888

Reputation: 4723

Better way to control which blocks of code to be executed than using if-then statement in Python?

I mostly work on data science/analysis. Often I need to test codes with and without random subsampling (if the original data is too large), sometimes show or hide results depending on if I am testing the code or to generate final results, as well as saving the final result/df in a .csv, among other things.

I have been using this strategy which is to create a section at the beginning of my codes called "Control Panel" and in which I have set up a number of "switches" etc and user-defined parameters, like so

# Control panel
save_file_switch = False # WARNING: will overwrite existing when == True
edge_date_inclusion = True # whether to include the last date in the range of inclusion criteria
testing_printout_switch = False
result_printout_switch = True
df_subsampling_switch = False # WARNING: make to sure turn off for final results
df_subsampling_n = 15000
random_seed = 888

Later in my code, the block of code to be switched on or off will be determined by the value of the switch

if testing_printout_switch == True:
    print (df_results) # print some results

So far, I found it as a useful organizational tool, but I wonder if there is better and more pythonic way to approach this.

Upvotes: 0

Views: 25

Answers (1)

TrebledJ
TrebledJ

Reputation: 8997

I would store all your flags, switches, and variables in a dictionary.

control_panel = {
  'save_file_switch': False,
  'edge_date_inclusion': True,
  'testing_printout_switch': False,
  'result_printout_switch': True,
  'df_subsampling_switch': False
  'df_subsampling_n': 15000
  'random_seed': 888
}

if control_panel['testing_printout_switch']:
    print(df_results)

Not entirely sure to what extent this is "Pythonic" though, but it gives you a centralised place to store your values while at the same time, keeping them unique and distinct.

Upvotes: 2

Related Questions