The add_argument method takes type keyword parameter. Any callable can be passed as an argument for this parameter.
Here,s a class which can be passed to the add_argument method and this may satisfy your requirement.
import argparse
class Arg(object):
def __init__(self, value):
self.value = value
if '=' in value:
self.value = value.split('=', 1)
def __str__(self):
return '{}=<{}>'.format(self.value[0], self.value[1]) if isinstance(self.value, list) else self.value
def __repr__(self):
if isinstance(self.value, list):
return repr('{}=<value>'.format(self.value[0]))
return '{}'.format(repr(self.value))
def __eq__(self, value):
return '{}'.format(repr(value)) == repr(self)
parser = argparse.ArgumentParser()
parser.add_argument('--param', default='ch1', choices=('ch1', 'ch2', 'ch3', 'ch4=<value>'), type=Arg)
args = parser.parse_args('--param ch4=123'.split())
print('choice {}, value {}'.format(args.param, repr(args.param.value)))
args = parser.parse_args([])
print('choice {}, value {}'.format(args.param, repr(args.param.value)))
args = parser.parse_args('--param ch3'.split())
print('choice {}, value {}'.format(args.param, repr(args.param.value)))
Output;
choice ch4=<123>, value ['ch4', '123']
choice ch1, value 'ch1'
choice ch3, value 'ch3'
args.param is an instance of Arg. args.param.value is either an str or a list if choice is ch4='some_value'