Skip to content

Commit c2aba3a

Browse files
argparse: Use Literal for action & nargs add_argument parameter types
1 parent 2279c87 commit c2aba3a

File tree

2 files changed

+30
-10
lines changed

2 files changed

+30
-10
lines changed

stdlib/argparse.pyi

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
import sys
2-
from typing import IO, Any, Callable, Generator, Generic, Iterable, NoReturn, Pattern, Protocol, Sequence, TypeVar, overload
2+
from typing import (
3+
IO,
4+
Any,
5+
Callable,
6+
Generator,
7+
Generic,
8+
Iterable,
9+
NewType,
10+
NoReturn,
11+
Pattern,
12+
Protocol,
13+
Sequence,
14+
TypeVar,
15+
overload,
16+
)
17+
from typing_extensions import Literal
318

419
if sys.version_info >= (3, 9):
520
__all__ = [
@@ -48,12 +63,13 @@ _ActionT = TypeVar("_ActionT", bound=Action)
4863
_ArgumentParserT = TypeVar("_ArgumentParserT", bound=ArgumentParser)
4964
_N = TypeVar("_N")
5065

51-
ONE_OR_MORE: str
52-
OPTIONAL: str
53-
PARSER: str
54-
REMAINDER: str
55-
SUPPRESS: str
56-
ZERO_OR_MORE: str
66+
ONE_OR_MORE: Literal["+"]
67+
OPTIONAL: Literal["?"]
68+
PARSER: Literal["A..."]
69+
REMAINDER: Literal["..."]
70+
_SUPPRESS_T = NewType("_SUPPRESS_T", str)
71+
SUPPRESS: _SUPPRESS_T # not using Literal because argparse sometimes compares SUPPRESS with is
72+
ZERO_OR_MORE: Literal["*"]
5773
_UNRECOGNIZED_ARGS_ATTR: str # undocumented
5874

5975
class ArgumentError(Exception):
@@ -89,14 +105,17 @@ class _ActionsContainer:
89105
def add_argument(
90106
self,
91107
*name_or_flags: str,
92-
action: str | type[Action] = ...,
93-
nargs: int | str = ...,
108+
action: Literal[
109+
"store", "store_const", "store_true", "store_false", "append", "append_const", "count", "help", "version", "extend"
110+
]
111+
| type[Action] = ...,
112+
nargs: int | Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="] | _SUPPRESS_T = ...,
94113
const: Any = ...,
95114
default: Any = ...,
96115
type: Callable[[str], _T] | FileType = ...,
97116
choices: Iterable[_T] | None = ...,
98117
required: bool = ...,
99-
help: str | None = ...,
118+
help: str | _SUPPRESS_T | None = ...,
100119
metavar: str | tuple[str, ...] | None = ...,
101120
dest: str | None = ...,
102121
version: str = ...,

tests/stubtest_allowlists/py3_common.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ xml.parsers.expat.expat_CAPI
236236
# Allowlist entries that cannot or should not be fixed
237237
# ==========
238238
_pydecimal.* # See comments in file
239+
argparse.SUPPRESS # See comment in file
239240
ast.NodeVisitor.visit_\w+ # Methods are discovered dynamically, see #3796
240241
# Weird special builtins that are typed as functions, but aren't functions
241242
builtins.copyright

0 commit comments

Comments
 (0)