Skip to content

Commit

Permalink
Make type ignores specific (#436)
Browse files Browse the repository at this point in the history
  • Loading branch information
mauvilsa authored Jan 25, 2024
1 parent 6a9df55 commit 65535dc
Show file tree
Hide file tree
Showing 21 changed files with 75 additions and 65 deletions.
6 changes: 3 additions & 3 deletions jsonargparse/_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -704,9 +704,9 @@ def get_subcommands(
subcommand_keys = [subcommand]

if fail_no_subcommand:
if subcommand is None and not (fail_no_subcommand and action._required): # type: ignore
if subcommand is None and not (fail_no_subcommand and action._required): # type: ignore[attr-defined]
return None, None
if action._required and subcommand not in action._name_parser_map: # type: ignore
if action._required and subcommand not in action._name_parser_map: # type: ignore[attr-defined]
# If subcommand is required and no subcommand is provided,
# present the user with a friendly error message to remind them of
# the available subcommands and to select one.
Expand All @@ -719,7 +719,7 @@ def get_subcommands(
f'expected "{dest}" to be one of {candidate_subcommands_str}, but it was not provided.'
)

return subcommand_keys, [action._name_parser_map.get(s) for s in subcommand_keys] # type: ignore
return subcommand_keys, [action._name_parser_map.get(s) for s in subcommand_keys] # type: ignore[misc]

@staticmethod
def get_subcommand(
Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def CLI(
caller = inspect.stack()[1][0]

if components is None:
module = inspect.getmodule(caller).__name__ # type: ignore
module = inspect.getmodule(caller).__name__ # type: ignore[union-attr]
components = [
v
for v in caller.f_locals.values()
Expand Down
12 changes: 11 additions & 1 deletion jsonargparse/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,17 @@
import sys
from contextlib import contextmanager
from contextvars import ContextVar
from typing import Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union, _GenericAlias # type: ignore
from typing import ( # type: ignore[attr-defined]
Dict,
Generic,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
_GenericAlias,
)

from ._namespace import Namespace
from ._type_checking import ArgumentParser
Expand Down
24 changes: 12 additions & 12 deletions jsonargparse/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
class ActionsContainer(SignatureArguments, argparse._ActionsContainer):
"""Extension of argparse._ActionsContainer to support additional functionalities."""

_action_groups: Sequence["_ArgumentGroup"] # type: ignore
_action_groups: Sequence["_ArgumentGroup"] # type: ignore[assignment]

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
Expand Down Expand Up @@ -134,7 +134,7 @@ def add_argument(self, *args, enable_path: bool = False, **kwargs):
if "choices" in kwargs and not isinstance(kwargs["choices"], (list, tuple)):
kwargs["choices"] = tuple(kwargs["choices"])
action = super().add_argument(*args, **kwargs)
action.logger = self._logger # type: ignore
action.logger = self._logger # type: ignore[attr-defined]
ActionConfigFile._add_print_config_argument(self, action)
ActionJsonnet._check_ext_vars_action(parser, action)
if is_meta_key(action.dest):
Expand All @@ -143,7 +143,7 @@ def add_argument(self, *args, enable_path: bool = False, **kwargs):
action.help = empty_help
if action.required:
parser.required_args.add(action.dest)
action._required = True # type: ignore
action._required = True # type: ignore[attr-defined]
action.required = False
return action

Expand Down Expand Up @@ -229,7 +229,7 @@ def __init__(
self.exit_on_error = exit_on_error
self.required_args: Set[str] = set()
self.save_path_content: Set[str] = set()
self.default_config_files = default_config_files # type: ignore
self.default_config_files = default_config_files # type: ignore[assignment]
self.default_meta = default_meta
self.default_env = default_env
self.env_prefix = env_prefix
Expand Down Expand Up @@ -667,10 +667,10 @@ def add_subcommands(self, required: bool = True, dest: str = "subcommand", **kwa
if "description" not in kwargs:
kwargs["description"] = "For more details of each subcommand, add it as an argument followed by --help."
with parser_context(parent_parser=self, lenient_check=True):
subcommands: _ActionSubCommands = super().add_subparsers(dest=dest, **kwargs) # type: ignore
subcommands: _ActionSubCommands = super().add_subparsers(dest=dest, **kwargs) # type: ignore[assignment]
if required:
self.required_args.add(dest)
subcommands._required = required # type: ignore
subcommands._required = required # type: ignore[attr-defined]
subcommands.required = False
subcommands.parent_parser = self
subcommands.env_prefix = get_env_var(self)
Expand Down Expand Up @@ -818,15 +818,15 @@ def check_overwrite(path):
raise NotImplementedError(f"multifile=True not supported for fsspec paths: {path}")
fsspec = import_fsspec("ArgumentParser.save")
with fsspec.open(path, "w") as f:
f.write(self.dump(cfg, **dump_kwargs)) # type: ignore
f.write(self.dump(cfg, **dump_kwargs)) # type: ignore[arg-type]
return

path_fc = Path(path, mode="fc")
check_overwrite(path_fc)

if not multifile:
with open(path_fc.absolute, "w") as f:
f.write(self.dump(cfg, **dump_kwargs)) # type: ignore
f.write(self.dump(cfg, **dump_kwargs)) # type: ignore[arg-type]

else:
cfg = cfg.clone()
Expand Down Expand Up @@ -866,7 +866,7 @@ def save_paths(cfg):
save_paths(cfg)
dump_kwargs["skip_check"] = True
with open(path_fc.absolute, "w") as f:
f.write(self.dump(cfg, **dump_kwargs)) # type: ignore
f.write(self.dump(cfg, **dump_kwargs)) # type: ignore[arg-type]

## Methods related to defaults ##

Expand Down Expand Up @@ -1151,7 +1151,7 @@ def instantiate_classes(
groups = [g for g in self._action_groups if hasattr(g, "instantiate_class") and g.dest not in skip]
components.extend(groups)

components.sort(key=lambda x: -len(split_key(x.dest))) # type: ignore
components.sort(key=lambda x: -len(split_key(x.dest))) # type: ignore[arg-type]
order = ActionLink.instantiation_order(self)
components = ActionLink.reorder(order, components)

Expand Down Expand Up @@ -1341,7 +1341,7 @@ def _check_value_key(self, action: argparse.Action, value: Any, key: str, cfg: O
leaf_key = split_key_leaf(key)[-1]
if leaf_key == action.dest:
return value
subparser = action._name_parser_map[leaf_key] # type: ignore
subparser = action._name_parser_map[leaf_key] # type: ignore[attr-defined]
subparser.check_config(value)
elif isinstance(action, _ActionConfigLoad):
if isinstance(value, str):
Expand Down Expand Up @@ -1395,7 +1395,7 @@ def default_config_files(self, default_config_files: Optional[List[Union[str, os
if not hasattr(self, "_default_config_files_group"):
group_title = "default config file locations"
group = _ArgumentGroup(self, title=group_title)
self._action_groups = [group] + self._action_groups # type: ignore
self._action_groups = [group] + self._action_groups # type: ignore[operator]
self._default_config_files_group = group
elif hasattr(self, "_default_config_files_group"):
self._action_groups = [g for g in self._action_groups if g != self._default_config_files_group]
Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class PercentTemplate(Template):
(?P<braced>[_a-z][_a-z0-9]*)\)s|
(?P<invalid>)
)
""" # type: ignore
""" # type: ignore[assignment]


class DefaultHelpFormatter(HelpFormatter):
Expand Down
14 changes: 7 additions & 7 deletions jsonargparse/_link_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def __init__(
)
else:
self.source = [
(s, find_parent_or_child_actions(parser, s, exclude=exclude)) for s in source # type: ignore
(s, find_parent_or_child_actions(parser, s, exclude=exclude)) for s in source # type: ignore[misc]
]

# Set and check target action
Expand Down Expand Up @@ -165,7 +165,7 @@ def __init__(
if is_target_subclass:
help_dest = f"{self.target[1].dest}.help"
for action in group._group_actions:
if action.dest == help_dest: # type: ignore
if action.dest == help_dest: # type: ignore[union-attr]
group._group_actions.remove(action)
break
if group._group_actions and all(isinstance(a, _ActionConfigLoad) for a in group._group_actions):
Expand All @@ -178,7 +178,7 @@ def __init__(
if target in parser.required_args:
parser.required_args.remove(target)
if is_target_subclass and not valid_target_leaf:
sub_add_kwargs = self.target[1].sub_add_kwargs # type: ignore
sub_add_kwargs = self.target[1].sub_add_kwargs # type: ignore[attr-defined]
if "linked_targets" not in sub_add_kwargs:
sub_add_kwargs["linked_targets"] = set()
subtarget = target.split(".init_args.", 1)[1]
Expand Down Expand Up @@ -272,7 +272,7 @@ def apply_parsing_links(parser: "ArgumentParser", cfg: Namespace) -> None:

subcommand, subparser = _ActionSubCommands.get_subcommand(parser, cfg, fail_no_subcommand=False)
if subcommand and subcommand in cfg:
ActionLink.apply_parsing_links(subparser, cfg[subcommand]) # type: ignore
ActionLink.apply_parsing_links(subparser, cfg[subcommand]) # type: ignore[arg-type]
if not hasattr(parser, "_links_group"):
return
for action in get_link_actions(parser, "parse"):
Expand All @@ -281,13 +281,13 @@ def apply_parsing_links(parser: "ArgumentParser", cfg: Namespace) -> None:
args = []
skip_link = False
for source_key, source_action in action.source:
if ActionTypeHint.is_subclass_typehint(source_action[0]) and source_key not in cfg: # type: ignore
if ActionTypeHint.is_subclass_typehint(source_action[0]) and source_key not in cfg: # type: ignore[index]
parser.logger.debug(
f"Link '{action.option_strings[0]}' ignored since source '{source_key}' not found in namespace."
)
skip_link = True
break
for source_action_n in [a for a in source_action if a.dest in cfg]: # type: ignore
for source_action_n in [a for a in source_action if a.dest in cfg]: # type: ignore[union-attr]
parser._check_value_key(source_action_n, cfg[source_action_n.dest], source_action_n.dest, None)
args.append(cfg[source_key])
if skip_link:
Expand Down Expand Up @@ -386,7 +386,7 @@ def set_target_value(action: "ActionLink", value: Any, cfg: Namespace, logger) -

if ActionTypeHint.is_subclass_typehint(target_action, all_subtypes=False, also_lists=True):
if target_key == target_action.dest:
target_action._check_type(value) # type: ignore
target_action._check_type(value) # type: ignore[attr-defined]
else:
parent = cfg.get(target_action.dest)
child_key = target_key[len(target_action.dest) + 1 :]
Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_loaders_dumpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
]


class DefaultLoader(getattr(yaml, "CSafeLoader", yaml.SafeLoader)): # type: ignore
class DefaultLoader(getattr(yaml, "CSafeLoader", yaml.SafeLoader)): # type: ignore[misc]
pass


Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_optionals.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def is_annotated_validator(typehint: type) -> bool:
return (
pydantic_support > 1
and is_annotated(typehint)
and any(get_module(m) in {"pydantic", "annotated_types"} for m in typehint.__metadata__) # type: ignore
and any(get_module(m) in {"pydantic", "annotated_types"} for m in typehint.__metadata__) # type: ignore[attr-defined]
)


Expand Down
12 changes: 6 additions & 6 deletions jsonargparse/_parameter_resolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class ParamData:


ParamList = List[ParamData]
parameter_attributes = [s[1:] for s in inspect.Parameter.__slots__] # type: ignore
parameter_attributes = [s[1:] for s in inspect.Parameter.__slots__] # type: ignore[attr-defined]
kinds = inspect._ParameterKind
ast_assign_type: Tuple[Type[ast.AST], ...] = (ast.AnnAssign, ast.Assign)
param_kwargs_pop_or_get = "**.pop|get():"
Expand Down Expand Up @@ -376,7 +376,7 @@ def group_parameters(params_list: List[ParamList]) -> ParamList:
non_get_pop_count = 0
params_dict = defaultdict(lambda: [])
for params in params_list:
if not (params[0].origin or "").startswith(param_kwargs_pop_or_get): # type: ignore
if not (params[0].origin or "").startswith(param_kwargs_pop_or_get): # type: ignore[union-attr]
non_get_pop_count += 1
for param in params:
if param.kind != kinds.POSITIONAL_ONLY:
Expand Down Expand Up @@ -445,7 +445,7 @@ def get_component_and_parent(
method_or_property: Optional[Union[str, Callable]] = None,
):
if is_subclass(function_or_class, ClassFromFunctionBase) and method_or_property in {None, "__init__"}:
function_or_class = function_or_class.wrapped_function # type: ignore
function_or_class = function_or_class.wrapped_function # type: ignore[union-attr]
method_or_property = None
elif inspect.isclass(get_generic_origin(function_or_class)) and method_or_property is None:
method_or_property = "__init__"
Expand Down Expand Up @@ -740,7 +740,7 @@ def get_parameters_args_and_kwargs(self) -> Tuple[ParamList, ParamList]:
elif self.parent and ast_is_super_call(node):
if ast_is_supported_super_call(node, self.self_name, self.log_debug):
params = get_mro_parameters(
node.func.attr, # type: ignore
node.func.attr, # type: ignore[attr-defined]
get_signature_parameters,
self.logger,
)
Expand Down Expand Up @@ -908,10 +908,10 @@ def get_parameters_from_pydantic_or_attrs(
if pydantic_support:
pydantic_model = is_pydantic_model(function_or_class)
if pydantic_model == 1:
fields_iterator = function_or_class.__fields__.items() # type: ignore
fields_iterator = function_or_class.__fields__.items() # type: ignore[union-attr]
get_field_data = get_field_data_pydantic1_model
elif pydantic_model > 1:
fields_iterator = function_or_class.model_fields.items() # type: ignore
fields_iterator = function_or_class.model_fields.items() # type: ignore[union-attr]
get_field_data = get_field_data_pydantic2_model
elif dataclasses.is_dataclass(function_or_class) and hasattr(function_or_class, "__pydantic_fields__"):
fields_iterator = dataclasses.fields(function_or_class)
Expand Down
10 changes: 5 additions & 5 deletions jsonargparse/_postponed_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def visit_Subscript(self, node: ast.Subscript) -> ast.Subscript:
if isinstance(node.value, ast.Name) and node.value.id in pep585_map:
value = self.new_name_load(pep585_map[node.value.id])
else:
value = node.value # type: ignore
value = node.value # type: ignore[assignment]
return ast.Subscript(
value=value,
slice=self.visit(node.slice),
Expand Down Expand Up @@ -259,7 +259,7 @@ def get_types(obj: Any, logger: Optional[logging.Logger] = None) -> dict:
try:
types = get_type_hints(obj, global_vars)
except Exception as ex1:
types = ex1 # type: ignore
types = ex1 # type: ignore[assignment]

if isinstance(types, dict) and all(not type_requires_eval(t) for t in types.values()):
return types
Expand All @@ -274,10 +274,10 @@ def get_types(obj: Any, logger: Optional[logging.Logger] = None) -> dict:
if isinstance(types, Exception):
if logger:
logger.debug(f"Failed to parse to source code for {obj}", exc_info=ex2)
raise type(types)(f"{repr(types)} + {repr(ex2)}") from ex2 # type: ignore
raise type(types)(f"{repr(types)} + {repr(ex2)}") from ex2 # type: ignore[arg-type]
return types

aliases = __builtins__.copy() # type: ignore
aliases = __builtins__.copy() # type: ignore[attr-defined]
aliases.update(global_vars)
ex = None
if isinstance(types, Exception):
Expand All @@ -291,7 +291,7 @@ def get_types(obj: Any, logger: Optional[logging.Logger] = None) -> dict:
if isinstance(node, ast.FunctionDef):
arg_asts = [(a.arg, a.annotation) for a in node.args.args + node.args.kwonlyargs]
else:
arg_asts = [(a.target.id, a.annotation) for a in node.body if isinstance(a, ast.AnnAssign)] # type: ignore
arg_asts = [(a.target.id, a.annotation) for a in node.body if isinstance(a, ast.AnnAssign)] # type: ignore[union-attr]

for name, annotation in arg_asts:
if annotation and (name not in types or type_requires_eval(types[name])):
Expand Down
8 changes: 4 additions & 4 deletions jsonargparse/_signatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def add_class_arguments(
defaults = default.lazy_get_init_args()
if defaults:
defaults = {prefix + k: v for k, v in defaults.items() if k not in skip}
self.set_defaults(**defaults) # type: ignore
self.set_defaults(**defaults) # type: ignore[attr-defined]

return added_args

Expand Down Expand Up @@ -246,7 +246,7 @@ def _add_signature_arguments(
for param in params:
if skip and param.name in skip:
continue
if prefix + param.name in self._option_string_actions: # type: ignore
if prefix + param.name in self._option_string_actions: # type: ignore[attr-defined]
raise ValueError(
f"Unable to add parameter '{param.name}' from {function_or_class} because "
f"argument '{prefix + param.name}' already exists."
Expand Down Expand Up @@ -498,12 +498,12 @@ def add_subclass_arguments(
if is_dataclass_like(baseclass):
raise ValueError("Not allowed for dataclass-like classes.")
if type(baseclass) is not tuple:
baseclass = (baseclass,) # type: ignore
baseclass = (baseclass,) # type: ignore[assignment]
if not baseclass or not all(inspect.isclass(c) for c in baseclass):
raise ValueError(f"Expected 'baseclass' argument to be a class or a tuple of classes: {baseclass}")

doc_group = None
if len(baseclass) == 1: # type: ignore
if len(baseclass) == 1: # type: ignore[arg-type]
doc_group = get_doc_short_description(baseclass[0], logger=self.logger)
group = self._create_group_if_requested(
baseclass,
Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_stubs_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:

def visit_If(self, node: ast.If) -> None:
test_ast = ast.parse("___test___ = 0")
test_ast.body[0].value = node.test # type: ignore
test_ast.body[0].value = node.test # type: ignore[attr-defined]
exec_vars = {"sys": sys}
with suppress(Exception):
exec(compile(test_ast, filename="<ast>", mode="exec"), exec_vars, exec_vars)
Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def __init__(self, typehint: Optional[Type] = None, enable_path: bool = False, *
discard = {typehint.__args__[n] for n, s in enumerate(subtype_supported) if not s}
kwargs["logger"].debug(f"Discarding unsupported subtypes {discard} from {typehint}")
subtypes = tuple(t for t, s in zip(typehint.__args__, subtype_supported) if s)
typehint = Union[subtypes] # type: ignore
typehint = Union[subtypes] # type: ignore[assignment]
self._typehint = typehint
self._enable_path = False if is_optional(typehint, Path) else enable_path
elif "_typehint" not in kwargs:
Expand Down
Loading

0 comments on commit 65535dc

Please sign in to comment.