type¶
By default, the parser reads command-line arguments in as simple
strings. However, quite often the command-line string should instead be
interpreted as another type, such as a float or int. The
type keyword for add_argument() allows any
necessary type-checking and type conversions to be performed.
If the type keyword is used with the default keyword, the type converter
is only applied if the default is a string.
The argument to type can be any callable that accepts a single string.
If the function raises ArgumentTypeError, TypeError, or
ValueError, the exception is caught and a nicely formatted error
message is displayed. No other exception types are handled.
Common built-in types and functions can be used as type converters:
import argparse
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument('count', type=int)
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('source_file', type=open)
parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
parser.add_argument('datapath', type=pathlib.Path)
User defined functions can be used as well:
>>>def hyphenated(string):
... return '-'.join([word[:4] for word in string.casefold().split()])
...
>>>parser = argparse.ArgumentParser()
>>>_ = parser.add_argument('short_title', type=hyphenated)
>>>parser.parse_args(['"The Tale of Two Cities"'])
Namespace(short_title='"the-tale-of-two-citi')
The bool() function is not recommended as a type converter. All it does
is convert empty strings to False and non-empty strings to True.
This is usually not what is desired.
In general, the type keyword is a convenience that should only be used for
simple conversions that can only raise one of the three supported exceptions.
Anything with more interesting error-handling or resource management should be
done downstream after the arguments are parsed.
For example, JSON or YAML conversions have complex error cases that require
better reporting than can be given by the type keyword. An
JSONDecodeError would not be well formatted and a
FileNotFound exception would not be handled at all.
Even FileType has its limitations for use with the type
keyword. If one argument uses FileType and then a subsequent argument fails,
an error is reported but the file is not automatically closed. In this case, it
would be better to wait until after the parser has run and then use the
with-statement to manage the files.
For type checkers that simply check against a fixed set of values, consider
using the choices keyword instead.