0

So, I have a python script for parsing and plotting data from text files. Argument handling is done with argparse module. The problem is, that some arguments are optional, e.g. one of the is used to add text annotations on the plot. This argument is sent to plotting function via **kwargs. My question is - what is the most pythonic way to handle those optional arguments? Some pseudo code here:

parser = argparse.ArgumentParser()
...
parser.add_argument("-o", "--options", nargs="+", help="additional options")
args = parser.parse_args()
...
def some_function(arguments, **kwargs):
   doing something with kwargs['options']
   return something
...
arguments = ...
some_function(arguments, options=args.options)

If options are not specified by default None value is assigned. And it causes some problems. What is more pythonic - somehow check 'options' within some_function? Or maybe parse arguments before some_function is called?

michal_2am
  • 211
  • 1
  • 3
  • 10
  • There are other SO questions about converting `argparse` arguments into `kwargs`, or accepting dictionary like inputs that could be passed on. Your `options` argument just produces a list of strings. – hpaulj Sep 06 '16 at 18:11
  • On use of `argparse` with `kwargs`: http://stackoverflow.com/questions/33712615/using-argparse-with-function-that-takes-kwargs-argument – hpaulj Sep 06 '16 at 18:13

2 Answers2

3

You can just provide an explicit empty list as the default.

parser.add_argument("-o", "--options", nargs="+", default=[])
chepner
  • 497,756
  • 71
  • 530
  • 681
1

use get and set a default value if the key is not found in the dict

def some_function(arguments, **kwargs):
   something = kwargs.get('options', 'Not found')
   return something

or an if statement

if 'option' in kwargs:
    pass # do something
danidee
  • 9,298
  • 2
  • 35
  • 55