The other answers are right - only string defaults are passed through the type
function. But there seems to be some reluctance to accept that logic.
Maybe this example will help:
import argparse
def mytype(astring):
return '['+astring+']'
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=mytype, default=1)
parser.add_argument('--bar', type=mytype, default='bar')
print parser.parse_args([])
print mytype(1)
produces:
0923:~/mypy$ python stack35429336.py
Namespace(bar='[bar]', foo=1)
Traceback (most recent call last):
File "stack35429336.py", line 8, in <module>
print mytype(1)
File "stack35429336.py", line 3, in mytype
return '['+astring+']'
TypeError: cannot concatenate 'str' and 'int' objects
I define a type
function - it takes a string input, and returns something - anything that I want. And raises an error if it can't return that. Here I just append some characters to the string.
When the default
is a string, it gets modified. But when it is a number (not a string) it is inserted without change. In fact as written mytype
raises an error if given a number.
The argparse
type
is often confused with the function type(a)
. The latter returns values like int
,str
,bool
. Plus the most common examples are int
and float
. But in argparse
float
is used as a function
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
type=bool
is a common error. Parsing boolean values with argparse. bool()
does not convert the string 'False'
to the boolean False
.
In [50]: bool('False')
Out[50]: True
If argparse
passed every default through the type
function, it would be difficult to place values like None
or False
in the namespace
. No builtin function converts a string to None
.
The key point is that the type
parameter is a function (callable
), not a casting operation or target.
For further clarification - or confusion - explore the default
and type
with nargs=2
or action='append'
.