Skip to content

Commit 791c065

Browse files
authored
Apply pyupgrade jsonargparse.* modules to use Python 3.9+ syntax (#798)
1 parent 5bfc380 commit 791c065

22 files changed

+186
-191
lines changed

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ Changed
3535
<https://github.com/omni-us/jsonargparse/pull/792>`__).
3636
- Non-parsing actions now have a common base class to ease identification
3737
(`#793 <https://github.com/omni-us/jsonargparse/pull/793>`__).
38+
- ``jsonargparse.*`` modules now use Python 3.9+ syntax (`#798
39+
<https://github.com/omni-us/jsonargparse/pull/798>`__).
3840

3941
Deprecated
4042
^^^^^^^^^^

jsonargparse/_actions.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from argparse import Action as ArgparseAction
88
from contextlib import contextmanager
99
from contextvars import ContextVar
10-
from typing import Any, Dict, List, Optional, Tuple, Type, Union
10+
from typing import Any, Optional, Union
1111

1212
from ._common import Action, NonParsingAction, is_not_subclass_type, is_subclass, parser_context
1313
from ._loaders_dumpers import get_loader_exceptions, load_value
@@ -48,8 +48,8 @@ def _is_branch_key(parser, key: str) -> bool:
4848
def _find_action_and_subcommand(
4949
parser: Union[ArgumentParser, ActionsContainer],
5050
dest: str,
51-
exclude: Optional[Union[Type[ArgparseAction], Tuple[Type[ArgparseAction], ...]]] = None,
52-
) -> Tuple[Optional[ArgparseAction], Optional[str]]:
51+
exclude: Optional[Union[type[ArgparseAction], tuple[type[ArgparseAction], ...]]] = None,
52+
) -> tuple[Optional[ArgparseAction], Optional[str]]:
5353
"""Finds an action in a parser given its destination key.
5454
5555
Args:
@@ -85,16 +85,16 @@ def _find_action_and_subcommand(
8585
def _find_action(
8686
parser: Union[ArgumentParser, ActionsContainer],
8787
dest: str,
88-
exclude: Optional[Union[Type[ArgparseAction], Tuple[Type[ArgparseAction], ...]]] = None,
88+
exclude: Optional[Union[type[ArgparseAction], tuple[type[ArgparseAction], ...]]] = None,
8989
) -> Optional[ArgparseAction]:
9090
return _find_action_and_subcommand(parser, dest, exclude=exclude)[0]
9191

9292

9393
def _find_parent_action_and_subcommand(
9494
parser: ArgumentParser,
9595
key: str,
96-
exclude: Optional[Union[Type[ArgparseAction], Tuple[Type[ArgparseAction], ...]]] = None,
97-
) -> Tuple[Optional[ArgparseAction], Optional[str]]:
96+
exclude: Optional[Union[type[ArgparseAction], tuple[type[ArgparseAction], ...]]] = None,
97+
) -> tuple[Optional[ArgparseAction], Optional[str]]:
9898
action, subcommand = _find_action_and_subcommand(parser, key, exclude=exclude)
9999
if action is None and "." in key:
100100
parts = split_key(key)
@@ -108,7 +108,7 @@ def _find_parent_action_and_subcommand(
108108
def _find_parent_action(
109109
parser: ArgumentParser,
110110
key: str,
111-
exclude: Optional[Union[Type[ArgparseAction], Tuple[Type[ArgparseAction], ...]]] = None,
111+
exclude: Optional[Union[type[ArgparseAction], tuple[type[ArgparseAction], ...]]] = None,
112112
) -> Optional[ArgparseAction]:
113113
return _find_parent_action_and_subcommand(parser, key, exclude=exclude)[0]
114114

@@ -304,7 +304,7 @@ def is_print_config_requested(parser):
304304

305305

306306
class _ActionConfigLoad(Action):
307-
def __init__(self, basetype: Optional[Type] = None, **kwargs):
307+
def __init__(self, basetype: Optional[type] = None, **kwargs):
308308
if len(kwargs) == 0:
309309
self._basetype = basetype
310310
else:
@@ -344,7 +344,7 @@ def check_type(self, value, parser):
344344

345345

346346
class _ActionHelpClassPath(NonParsingAction):
347-
sub_add_kwargs: Dict[str, Any] = {}
347+
sub_add_kwargs: dict[str, Any] = {}
348348

349349
@classmethod
350350
def get_help_types(cls, typehint) -> Optional[tuple]:
@@ -727,7 +727,7 @@ def get_subcommands(
727727
cfg: Namespace,
728728
prefix: str = "",
729729
fail_no_subcommand: bool = True,
730-
) -> Tuple[Optional[List[str]], Optional[List[ArgumentParser]]]:
730+
) -> tuple[Optional[list[str]], Optional[list[ArgumentParser]]]:
731731
"""Returns subcommand names and corresponding subparsers."""
732732
if parser._subcommands_action is None:
733733
return None, None
@@ -783,7 +783,7 @@ def get_subcommand(
783783
cfg: Namespace,
784784
prefix: str = "",
785785
fail_no_subcommand: bool = True,
786-
) -> Tuple[Optional[str], Optional[ArgumentParser]]:
786+
) -> tuple[Optional[str], Optional[ArgumentParser]]:
787787
"""Returns a single subcommand name and corresponding subparser."""
788788
subcommands, subparsers = _ActionSubCommands.get_subcommands(
789789
parser,

jsonargparse/_cli.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Simple creation of command line interfaces."""
22

33
import inspect
4-
from typing import Any, Callable, Dict, List, Optional, Type, Union
4+
from typing import Any, Callable, Optional, Union
55

66
from ._actions import ActionConfigFile, _ActionPrintConfig, remove_actions
77
from ._core import ArgumentParser
@@ -17,9 +17,9 @@
1717
]
1818

1919

20-
ComponentType = Union[Callable, Type]
21-
DictComponentsType = Dict[str, Union[ComponentType, "DictComponentsType"]]
22-
ComponentsType = Optional[Union[ComponentType, List[ComponentType], DictComponentsType]]
20+
ComponentType = Union[Callable, type]
21+
DictComponentsType = dict[str, Union[ComponentType, "DictComponentsType"]]
22+
ComponentsType = Optional[Union[ComponentType, list[ComponentType], DictComponentsType]]
2323

2424

2525
def CLI(*args, **kwargs):
@@ -29,12 +29,12 @@ def CLI(*args, **kwargs):
2929

3030
def auto_cli(
3131
components: ComponentsType = None,
32-
args: Optional[List[str]] = None,
32+
args: Optional[list[str]] = None,
3333
config_help: str = default_config_option_help,
34-
set_defaults: Optional[Dict[str, Any]] = None,
34+
set_defaults: Optional[dict[str, Any]] = None,
3535
as_positional: bool = True,
3636
fail_untyped: bool = True,
37-
parser_class: Type[ArgumentParser] = ArgumentParser,
37+
parser_class: type[ArgumentParser] = ArgumentParser,
3838
**kwargs,
3939
):
4040
"""Simple creation of command line interfaces.

jsonargparse/_common.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,9 @@
77
from contextvars import ContextVar
88
from typing import ( # type: ignore[attr-defined]
99
Callable,
10-
Dict,
1110
Generic,
12-
List,
1311
Optional,
1412
Protocol,
15-
Tuple,
16-
Type,
1713
TypeVar,
1814
Union,
1915
_GenericAlias,
@@ -51,11 +47,11 @@
5147

5248

5349
class InstantiatorCallable(Protocol):
54-
def __call__(self, class_type: Type[ClassType], *args, **kwargs) -> ClassType:
50+
def __call__(self, class_type: type[ClassType], *args, **kwargs) -> ClassType:
5551
pass # pragma: no cover
5652

5753

58-
InstantiatorsDictType = Dict[Tuple[type, bool], InstantiatorCallable]
54+
InstantiatorsDictType = dict[tuple[type, bool], InstantiatorCallable]
5955

6056

6157
parent_parser: ContextVar[Optional[ArgumentParser]] = ContextVar("parent_parser", default=None)
@@ -64,7 +60,7 @@ def __call__(self, class_type: Type[ClassType], *args, **kwargs) -> ClassType:
6460
lenient_check: ContextVar[Union[bool, str]] = ContextVar("lenient_check", default=False)
6561
load_value_mode: ContextVar[Optional[str]] = ContextVar("load_value_mode", default=None)
6662
class_instantiators: ContextVar[Optional[InstantiatorsDictType]] = ContextVar("class_instantiators", default=None)
67-
nested_links: ContextVar[List[dict]] = ContextVar("nested_links", default=[])
63+
nested_links: ContextVar[list[dict]] = ContextVar("nested_links", default=[])
6864
applied_instantiation_links: ContextVar[Optional[set]] = ContextVar("applied_instantiation_links", default=None)
6965
path_dump_preserve_relative: ContextVar[bool] = ContextVar("path_dump_preserve_relative", default=False)
7066

@@ -287,7 +283,7 @@ def is_pure_dataclass(cls) -> bool:
287283
return all(dataclasses.is_dataclass(c) for c in classes)
288284

289285

290-
not_subclass_type_selectors: Dict[str, Callable[[Type], Union[bool, int]]] = {
286+
not_subclass_type_selectors: dict[str, Callable[[type], Union[bool, int]]] = {
291287
"final": is_final_class,
292288
"dataclass": is_pure_dataclass,
293289
"pydantic": is_pydantic_model,
@@ -303,15 +299,15 @@ def is_not_subclass_type(cls) -> bool:
303299
return any(validator(cls) for validator in not_subclass_type_selectors.values())
304300

305301

306-
def default_class_instantiator(class_type: Type[ClassType], *args, **kwargs) -> ClassType:
302+
def default_class_instantiator(class_type: type[ClassType], *args, **kwargs) -> ClassType:
307303
return class_type(*args, **kwargs)
308304

309305

310306
class ClassInstantiator:
311307
def __init__(self, instantiators: InstantiatorsDictType) -> None:
312308
self.instantiators = instantiators
313309

314-
def __call__(self, class_type: Type[ClassType], *args, **kwargs) -> ClassType:
310+
def __call__(self, class_type: type[ClassType], *args, **kwargs) -> ClassType:
315311
for (cls, subclasses), instantiator in self.instantiators.items():
316312
if class_type is cls or (subclasses and is_subclass(class_type, cls)):
317313
param_names = set(inspect.signature(instantiator).parameters)

jsonargparse/_completions.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from enum import Enum
1111
from importlib.util import find_spec
1212
from subprocess import PIPE, Popen
13-
from typing import List, Literal, Union
13+
from typing import Literal, Union
1414

1515
from ._actions import ActionConfigFile, _ActionConfigLoad, _ActionHelpClassPath, remove_actions
1616
from ._common import NonParsingAction, get_optionals_as_positionals_actions, get_parsing_setting
@@ -153,10 +153,12 @@ def shtab_prepare_action(action, parser) -> None:
153153
elif isinstance(action, ActionTypeHint):
154154
typehint = action._typehint
155155
if get_typehint_origin(typehint) == Union:
156+
assert hasattr(typehint, "__args__")
156157
subtypes = [s for s in typehint.__args__ if s not in {NoneType, str, dict, list, tuple, bytes}]
157158
if len(subtypes) == 1:
158159
typehint = subtypes[0]
159160
if is_subclass(typehint, Path):
161+
assert hasattr(typehint, "_mode")
160162
if "f" in typehint._mode:
161163
complete = shtab.FILE
162164
elif "d" in typehint._mode:
@@ -230,7 +232,7 @@ def add_bash_typehint_completion(parser, action, message, choices) -> None:
230232
action.complete = {"bash": fn_name}
231233

232234

233-
def get_typehint_choices(typehint, prefix, parser, skip, choices=None, added_subclasses=None) -> List[str]:
235+
def get_typehint_choices(typehint, prefix, parser, skip, choices=None, added_subclasses=None) -> list[str]:
234236
if choices is None:
235237
choices = []
236238
if not added_subclasses:
@@ -265,7 +267,7 @@ def get_typehint_choices(typehint, prefix, parser, skip, choices=None, added_sub
265267
return [] if choices == ["null"] else choices
266268

267269

268-
def add_subactions_and_get_subclass_choices(typehint, prefix, parser, skip, added_subclasses) -> List[str]:
270+
def add_subactions_and_get_subclass_choices(typehint, prefix, parser, skip, added_subclasses) -> list[str]:
269271
choices = []
270272
paths = get_all_subclass_paths(typehint)
271273
init_args = defaultdict(list)
@@ -303,7 +305,7 @@ def add_subactions_and_get_subclass_choices(typehint, prefix, parser, skip, adde
303305
return choices
304306

305307

306-
def get_help_class_choices(typehint) -> List[str]:
308+
def get_help_class_choices(typehint) -> list[str]:
307309
choices = []
308310
if get_typehint_origin(typehint) == Union:
309311
for subtype in typehint.__args__:

0 commit comments

Comments
 (0)