Reputation: 19
In order to parse some args via cmd line, I've a "switch case" written with if .. elif
if arg == 1:
..something...
elif arg >= 2 and arg < 4:
..something else ...
elif arg < 6:
..something else ...
else:
..something else ...
above, elif arg < 6:
could be replaced by: elif arg == 4 or arg == 5:
this get's a bit messy when there are more argument values to check.
What could be the most efficient and easy way to read the code?
Upvotes: 1
Views: 180
Reputation: 2161
If your goal really is to parse a command line, use optparse if in python 2.6 or lower, argparse for later python versions. There is also a really nice little package called aaargh that makes for some really concise code. You will need to use decorators with that, so probably save that for a later project.
Use optparse or argparse, you can use things like -d somedir or --dir=somedir. It allows you to handle both optional parameters in any order, as well as required ones.
It also will generate a help message, if the command line does not meet your requirements.
Upvotes: 0
Reputation: 17246
You could try something like this:
def case_A():
.. something ..
def case_B():
.. something ..
def case_C():
.. something ..
def case_else():
.. something ..
{
1: case_A,
2: case_B,
3: case_B,
4: case_C,
5: case_C
}.get(arg, case_else)()
Upvotes: 2