0

I am trying to figure out a way to set a default value for some optional argparse arguments depending on the value of a required argument.

For example:

#Required args
parser.add_argument('directory', type=str, default='MIPs')
parser.add_argument('channels', type=str, default='CamA_ch0,CamB_ch0')

channel_list = parser.channels.split(',')

#Optional args
parser.add_argument('--opacity', type=float, nargs='+', defualt=[1.0 for i in channel_list])            
parser.add_argument('--contrast_limits', type=float, nargs='+', default=[None for i in channel_list])   
parser.add_argument('--gammma', type=float, nargs='+', default=[1.0 for i in channel_list])             
parser.add_argument('--colormaps', type=str, default='blue,green,red,magenta,yellow,orange,cyan')       
parser.add_argument('--blending', type=str, default=''.join(['addative,' for i in channel_list]))       
parser.add_argument('--interpolation', type=str, default=''.join(['nearest,' for i in channel_list])) 

I am eventually passing in these arguments into another function, where they are optional arguments like this:

viewer.add_image(
    timelapse, name=channel, opacity=args.opacity[index], 
    contrast_limits=args.contrast_limits[index], gamma=args.gamma[index],
    colormap=args.colormaps.split(',')[index], blending=args.blending.split(',')[index],
    interpolation=args.interpolation.split(',')[index] )

This doesn't worst as I would have to call ArgumentParser() first, but I cannot think of another way other than making these default value lists longer than I would ever need.

Ideally, I would like to not even pass these arguments into the add_image() function if I never use them, but I also cannot think of a good way to do that.

  • 1
    Something like this has been asked many times. You can't do this directly with `argparse`. But you could use `parser_known_args` to get the required value, and then define a new parser that uses that value as a default. Or do the checking after parsing, substituting a `None` default with the desired default. Don't make things more difficult for yourself than necessary. – hpaulj Feb 15 '22 at 05:53
  • @hpaulj does `parser_known_args` work when setting all those arguments in the same command line? As far as I know that is how they are going to be passed into my script – Myrkgard Feb 15 '22 at 06:18
  • 1
    https://stackoverflow.com/questions/70683449/use-an-argumentparser-argument-as-a-default-value-of-another-argument, https://stackoverflow.com/questions/20048048/argparse-default-option-based-on-another-option, https://stackoverflow.com/questions/45686317/python-argparse-set-default-value-of-a-parameter-to-another-parameter – hpaulj Feb 15 '22 at 06:32

0 Answers0