Skip to content

Commit a090181

Browse files
argparse: Use Literal for action & nargs add_argument parameter types (#7329)
1 parent 953f815 commit a090181

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

stdlib/argparse.pyi

Lines changed: 29 additions & 9 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,14 @@ _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 | str # not using Literal because argparse sometimes compares SUPPRESS with is
72+
# the | str is there so that foo = argparse.SUPPRESS; foo = "test" checks out in mypy
73+
ZERO_OR_MORE: Literal["*"]
5774
_UNRECOGNIZED_ARGS_ATTR: str # undocumented
5875

5976
class ArgumentError(Exception):
@@ -89,8 +106,11 @@ class _ActionsContainer:
89106
def add_argument(
90107
self,
91108
*name_or_flags: str,
92-
action: str | type[Action] = ...,
93-
nargs: int | str = ...,
109+
action: Literal[
110+
"store", "store_const", "store_true", "store_false", "append", "append_const", "count", "help", "version", "extend"
111+
]
112+
| type[Action] = ...,
113+
nargs: int | Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="] | _SUPPRESS_T = ...,
94114
const: Any = ...,
95115
default: Any = ...,
96116
type: Callable[[str], _T] | FileType = ...,

0 commit comments

Comments
 (0)