0

So here is my scenario:

I have a python script, call it myscript.py. Within this script, different types of data can be generated etc. When I run this script from the command line, I want to be able to input a 'plotting mode', like 1, 2, 3, etc. So far I know how to do that.

What I want to do with those plotting modes however, is where I am stuck.

Essentially, I want to say that if the plotting mode is 1, then execute a particular plotting routine, with say, 5 subplots, showing particular data in a certain way.

If the plotting mode is 2 lets say, then execute a completely different plotting routine, with 3 data types, showing them in a very particular way, etc etc.

I am not clear on how exactly go to about doing that. I suppose the easiest way is to simply map the plotting mode to an if/else statement, which calls particular functions, but I was wondering if there was a more elegant way?

Thanks

TheGrapeBeyond
  • 543
  • 2
  • 8
  • 19
  • I don't understand the problem, if you know how to access the script parameters, why you can't use if for code flow ? – Eric Nordelo Galiano Sep 20 '18 at 20:10
  • 1
    A skeleton code example will help understanding the question and then answering it. – Udit Hari Vashisht Sep 20 '18 at 20:16
  • @EricNordeloGaliano It seems confusing I know. This is more a question of elegance than utility I am seeing. Basically, I have all options under a giant if-else statement now, where if the mode is 'blah', I run function 'plot_blah', and if the mode is 'foo', I run 'plot_foo'. But that means I have to define those functions as so. I was wondering if there was a more elegant way. – TheGrapeBeyond Sep 20 '18 at 20:27

1 Answers1

0

You could use a dictionary to map mode to function:

mode = ... # this is the mode you obtain from the call
lookup = {"1" : function1, "2" : function2, ...}
# call function from lookup depending on mode
lookup[mode]()

You could also obtain the function to be called via a string that contains the mode name

locals()["function{}".format(mode)]()

Of course this only works if function1, function2 etc all take the same (or no) arguments. If you want to call different functions with different arguments, using if/else is probably a good way too.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712