python / python/cpython

argparse: document exceptions, subclass from SystemExit and ArgparseError

未关闭
#93,873 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

docs
主要语言
Python
星标
77.2k
派生
36k
平均合并
1 天 9 小时
30 天内合并 PR
558

描述

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 issue 中提到的 argparse 入口点开始:ArgumentParser、parse_args 和 ArgumentError;然后查看 argparse 文档中关于退出方法的部分以及 Python 帮助输出。在提出更改和文档更新之前,确定预期的异常层次结构、对引发的异常类型的保证,以及专门的异常子部分的范围。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
cli, documentation
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。