This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Actions

Finally, you can assign actions to an argument.

The default action that we have been using is store (store the value).

Here are some other actions:

  • Store a constant if the user specifies a **flag(( (an option without any value).
parser = argparse.ArgumentParser()

parser.add_argument("--magic", action="store_const", const=42)  

args = parser.parse_args()
print(args)   # Namespace(magic=42) if --magic is specified, Namespace(magic=None) otherwise.
  • Store True/False if the user specifies a flag
parser.add_argument("--play", action="store_true")  
parser.add_argument("--sleep", action="store_false")  
  • Append instances of an argument into a list. Allows users to specify more than one value for an option.
parser = argparse.ArgumentParser()
parser.add_argument("--input", action="append")
print(parser.parse_args())   
$ python test.py --input 1 --input 2 --input 3 --input 4
Namespace(input=['1', '2', '3', '4'])