Convert to integer

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('number', help='the number to take to the square', type=int)
args = parser.parse_args()

print(args.number * args.number)

$ abc
usage: [-h] number error: argument number: invalid int value: 'abc'

We got a much better error message as argparse already found out the argument was a string and not a number as expected.

$ 23

The type parameter can be used to define the type restriction and type conversion of the attributes.