Skip to content

argparse: Use Literal for action & nargs add_argument parameter types #7329

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 21, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions stdlib/argparse.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import sys
from typing import IO, Any, Callable, Generator, Generic, Iterable, NoReturn, Pattern, Protocol, Sequence, TypeVar, overload
from typing import (
IO,
Any,
Callable,
Generator,
Generic,
Iterable,
NewType,
NoReturn,
Pattern,
Protocol,
Sequence,
TypeVar,
overload,
)
from typing_extensions import Literal

if sys.version_info >= (3, 9):
__all__ = [
Expand Down Expand Up @@ -48,12 +63,14 @@ _ActionT = TypeVar("_ActionT", bound=Action)
_ArgumentParserT = TypeVar("_ArgumentParserT", bound=ArgumentParser)
_N = TypeVar("_N")

ONE_OR_MORE: str
OPTIONAL: str
PARSER: str
REMAINDER: str
SUPPRESS: str
ZERO_OR_MORE: str
ONE_OR_MORE: Literal["+"]
OPTIONAL: Literal["?"]
PARSER: Literal["A..."]
REMAINDER: Literal["..."]
_SUPPRESS_T = NewType("_SUPPRESS_T", str)
SUPPRESS: _SUPPRESS_T | str # not using Literal because argparse sometimes compares SUPPRESS with is
# the | str is there so that foo = argparse.SUPPRESS; foo = "test" checks out in mypy
ZERO_OR_MORE: Literal["*"]
_UNRECOGNIZED_ARGS_ATTR: str # undocumented

class ArgumentError(Exception):
Expand Down Expand Up @@ -89,8 +106,11 @@ class _ActionsContainer:
def add_argument(
self,
*name_or_flags: str,
action: str | type[Action] = ...,
nargs: int | str = ...,
action: Literal[
"store", "store_const", "store_true", "store_false", "append", "append_const", "count", "help", "version", "extend"
]
| type[Action] = ...,
nargs: int | Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="] | _SUPPRESS_T = ...,
const: Any = ...,
default: Any = ...,
type: Callable[[str], _T] | FileType = ...,
Expand Down