There seems to be some confusion as to what type=bool
and type='bool'
might mean. Should one (or both) mean 'run the function bool()
, or 'return a boolean'? As it stands type='bool'
means nothing. add_argument
gives a 'bool' is not callable
error, same as if you used type='foobar'
, or type='int'
.
But argparse
does have registry that lets you define keywords like this. It is mostly used for action
, e.g. `action='store_true'. You can see the registered keywords with:
parser._registries
which displays a dictionary
{'action': {None: argparse._StoreAction,
'append': argparse._AppendAction,
'append_const': argparse._AppendConstAction,
...
'type': {None: <function argparse.identity>}}
There are lots of actions defined, but only one type, the default one, argparse.identity
.
This code defines a 'bool' keyword:
def str2bool(v):
#susendberg's function
return v.lower() in ("yes", "true", "t", "1")
p = argparse.ArgumentParser()
p.register('type','bool',str2bool) # add type keyword to registries
p.add_argument('-b',type='bool') # do not use 'type=bool'
# p.add_argument('-b',type=str2bool) # works just as well
p.parse_args('-b false'.split())
Namespace(b=False)
parser.register()
is not documented, but also not hidden. For the most part the programmer does not need to know about it because type
and action
take function and class values. There are lots of stackoverflow examples of defining custom values for both.
In case it isn't obvious from the previous discussion, bool()
does not mean 'parse a string'. From the Python documentation:
bool(x): Convert a value to a Boolean, using the standard truth testing procedure.
Contrast this with
int(x): Convert a number or string x to an integer.
parser.add_argument('--feature', dest='feature', default=False, action='store_true')
. This solution will gurantee you always get abool
type with valueTrue
orFalse
. (This solution has a constraint: your option must have a default value.) – Trevor Boyd Smithparser.add_argument('--feature', dest='feature', type=lambda x:bool(distutils.util.strtobool(x)))
. When the option is used, this solution will ensure abool
type with value ofTrue
orFalse
. When the option is not used you will getNone
. (distutils.util.strtobool(x)
is from another stackoverflow question) – Trevor Boyd Smithparser.add_argument('--my_bool', action='store_true', default=False)
– AruniRC