python / python/cpython

argparse: document exceptions, subclass from SystemExit and ArgparseError

Open
#93,873 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

docs
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

There are many problems with exit status people encounter using argparse (and some of them are open, e.g. https://github.com/python/cpython/issues/85427).

It is reasonable and consistent with other code that it raises SystemExit (in case of unrecognized arguments).
However, this is not flexible and requires pretty much work from users if they want to catch this error, and not exit (there are many alternatives (which in itself contradicts the Zen of Python), the default proposes to subclass the ArgumentParser).

Why can't argparse just subclass SystemExit? This is usually a good guideline for a module to create its own exception classes.

Also, all three argparse exceptions could derive from one argparse exception class (to make their interception easier) (in the title I suggested ArgparseError, but a better name might be found). However, this is not so crucial as this SystemExit: I run a big function in one place of which there is parse_args; I don't want to attribute all SystemExit-s to argparse when I catch exceptions from that function (for now I had to create my own subclass of SystemExit raised from the line with parse_args).

And (should it be a separate feature request?) could there be a subsection dedicated to exceptions in the argparse module documentation? I had to read Python help to understand the initialisation of ArgumentError.
If argparse could guarantee the types of exceptions that it can raise, that would be ideal.

Originally posted by @ericvsmith in https://github.com/python/cpython/issues/83514#issuecomment-1093850932

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the argparse entry points mentioned in the issue: ArgumentParser, parse_args, and ArgumentError, then review the argparse documentation's exiting-methods section and Python help output. Determine the intended exception hierarchy, guarantees for raised exception types, and the scope of a dedicated exceptions subsection before proposing changes and documentation updates.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
cli, documentation
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.