Build a Mini Command-Line Parser

medium
Unit 14 · Parsing & Decorators0/3 to milestone

Every script ends up needing flags. Build a small version of argparse to see how it works.

Implement parse_args(argv, spec):

  • spec maps option names to definitions, e.g. {"model": {"type": str, "default": "small"}, "epochs": {"type": int, "required": True}, "verbose": {"flag": True}}.
  • Options can be given as --name value or --name=value. Flags ("flag": True) take no value and become True when present (default False).
  • Anything that doesn't start with -- is a positional argument, collected in order under "_args". A lone -- means everything after it is positional.
  • Convert values with the option's type (default str). Missing options get their default, or None.
  • Raise ValueError (with a helpful message) for an unknown option, a missing value, a value that fails type conversion, a value given to a flag, or a missing required option.

Return a dict of option values plus "_args".

#parsing#cli#design2 visible + 4 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Build a Mini Command-Line Parser · TechGradify