python / python/cpython

argparse: how to allow option values starting with dash

オープン
#138,950 コメント 3 件 リアクション 1 件 担当者 1 名 GitHub で見る

@serhiy-storchaka がすでに取り組んでいます。

2025年9月15日 から。

3.13 stdlib type-bug
主要言語
Python
スター
77.2k
フォーク
36k
PR マージ指標
PR 指標を取得中

説明

Documentation

The difference between nargs=None and nargs=1 should probably be explained in the docs in the section about arguments containing -.
Using nargs=1 actually allows to work around some issues with having an option value starting with a dash. Which has been a long standing issue with argparse as shown with the issue #53580.

Here is an example of the difference:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--nargs-is-1", nargs=1)
>>> parser.parse_args(["--nargs-is-1", "-3,5-10"])
Namespace(nargs_is_none=None, nargs_is_1=['-3,5-10'])
>>> parser.add_argument("--nargs-is-none")
>>> parser.parse_args(["--nargs-is-none", "-3,5-10"])
usage: [-h] [--nargs-is-none NARGS_IS_NONE] [--nargs-is-1 NARGS_IS_1]
: error: argument --nargs-is-none: expected one argument

This trick, however, only covers the case where the number of arguments to gobble up is fixed. People wanting a variable number of arguments to their options would need a more involved disambiguation technique that argparse is incapable of for now. (Although I guess something could be implemented by labeling ambiguous arguments as ambiguous and introduce values of nargs for different treatment of those. But that's beside the scope of this issue.)

Incidentally, this trick has been made to work only one year ago by the commit 3f27153e077d7e9448e2f081275931968b40cc74. Not sure if that was an intended consequence, but now it works and I'm here for it. :)

That documentation section (arguments containing -) suggests that argparse uses a heuristics to determine whether an argument is positional or optional. Maybe the gist of the heuristics could be laid out on so that users don't have to guess or read the code to get argparse to behave the way they want?

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。