typestar

argparse in Python

A parser built from declarations gives you help, types and errors for free.

import argparse

parser = argparse.ArgumentParser(prog="typestar", description="practice")
parser.add_argument("lang", help="language to practice")
parser.add_argument("-s", "--seconds", type=int, default=60)
parser.add_argument("--editor", action="store_true")
parser.add_argument("--tour", choices=["basics", "pythonic"], default="basics")

args = parser.parse_args(["python", "-s", "300", "--editor"])
print(args.lang, args.seconds, args.editor, args.tour)
print(vars(args))

How it works

  1. add_argument with a dash prefix makes it optional.
  2. type converts and rejects bad input before your code runs.
  3. parse_args on a list is how you test a parser.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
477
Tokens
143
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 1 of 4 in Command line, step 22 of 41 in Domain tools.

← Previous Next →