From 65535dc5fdc76faafe3ddbbdb22557f9d0c020c8 Mon Sep 17 00:00:00 2001 From: Mauricio Villegas <5780272+mauvilsa@users.noreply.github.com> Date: Thu, 25 Jan 2024 04:13:11 -0500 Subject: [PATCH] Make type ignores specific (#436) --- jsonargparse/_actions.py | 6 ++--- jsonargparse/_cli.py | 2 +- jsonargparse/_common.py | 12 +++++++++- jsonargparse/_core.py | 24 +++++++++---------- jsonargparse/_formatters.py | 2 +- jsonargparse/_link_arguments.py | 14 +++++------ jsonargparse/_loaders_dumpers.py | 2 +- jsonargparse/_optionals.py | 2 +- jsonargparse/_parameter_resolvers.py | 12 +++++----- jsonargparse/_postponed_annotations.py | 10 ++++---- jsonargparse/_signatures.py | 8 +++---- jsonargparse/_stubs_resolver.py | 2 +- jsonargparse/_typehints.py | 2 +- jsonargparse/_util.py | 10 ++++---- jsonargparse/typing.py | 4 ++-- jsonargparse_tests/test_dataclass_like.py | 6 ++--- .../test_parameter_resolvers.py | 4 ++-- .../test_postponed_annotations.py | 2 +- jsonargparse_tests/test_signatures.py | 6 ++--- jsonargparse_tests/test_typehints.py | 6 ++--- jsonargparse_tests/test_util.py | 4 ++-- 21 files changed, 75 insertions(+), 65 deletions(-) diff --git a/jsonargparse/_actions.py b/jsonargparse/_actions.py index b58562b3..27730628 100644 --- a/jsonargparse/_actions.py +++ b/jsonargparse/_actions.py @@ -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. @@ -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( diff --git a/jsonargparse/_cli.py b/jsonargparse/_cli.py index f6b7eb20..80ac8af6 100644 --- a/jsonargparse/_cli.py +++ b/jsonargparse/_cli.py @@ -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() diff --git a/jsonargparse/_common.py b/jsonargparse/_common.py index 9c17c7ad..cc3f5483 100644 --- a/jsonargparse/_common.py +++ b/jsonargparse/_common.py @@ -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 diff --git a/jsonargparse/_core.py b/jsonargparse/_core.py index 8f1d2f92..c48df815 100644 --- a/jsonargparse/_core.py +++ b/jsonargparse/_core.py @@ -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) @@ -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): @@ -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 @@ -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 @@ -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) @@ -818,7 +818,7 @@ 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") @@ -826,7 +826,7 @@ def check_overwrite(path): 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() @@ -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 ## @@ -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) @@ -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): @@ -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] diff --git a/jsonargparse/_formatters.py b/jsonargparse/_formatters.py index 9ddc566b..408e0749 100644 --- a/jsonargparse/_formatters.py +++ b/jsonargparse/_formatters.py @@ -45,7 +45,7 @@ class PercentTemplate(Template): (?P[_a-z][_a-z0-9]*)\)s| (?P) ) - """ # type: ignore + """ # type: ignore[assignment] class DefaultHelpFormatter(HelpFormatter): diff --git a/jsonargparse/_link_arguments.py b/jsonargparse/_link_arguments.py index a54acc76..709edb5c 100644 --- a/jsonargparse/_link_arguments.py +++ b/jsonargparse/_link_arguments.py @@ -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 @@ -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): @@ -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] @@ -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"): @@ -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: @@ -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 :] diff --git a/jsonargparse/_loaders_dumpers.py b/jsonargparse/_loaders_dumpers.py index ec6c2ca3..c22e5509 100644 --- a/jsonargparse/_loaders_dumpers.py +++ b/jsonargparse/_loaders_dumpers.py @@ -16,7 +16,7 @@ ] -class DefaultLoader(getattr(yaml, "CSafeLoader", yaml.SafeLoader)): # type: ignore +class DefaultLoader(getattr(yaml, "CSafeLoader", yaml.SafeLoader)): # type: ignore[misc] pass diff --git a/jsonargparse/_optionals.py b/jsonargparse/_optionals.py index fb9ec102..d540c8c0 100644 --- a/jsonargparse/_optionals.py +++ b/jsonargparse/_optionals.py @@ -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] ) diff --git a/jsonargparse/_parameter_resolvers.py b/jsonargparse/_parameter_resolvers.py index 7ae36d35..6d1f3744 100644 --- a/jsonargparse/_parameter_resolvers.py +++ b/jsonargparse/_parameter_resolvers.py @@ -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():" @@ -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: @@ -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__" @@ -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, ) @@ -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) diff --git a/jsonargparse/_postponed_annotations.py b/jsonargparse/_postponed_annotations.py index aff89242..11168a0b 100644 --- a/jsonargparse/_postponed_annotations.py +++ b/jsonargparse/_postponed_annotations.py @@ -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), @@ -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 @@ -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): @@ -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])): diff --git a/jsonargparse/_signatures.py b/jsonargparse/_signatures.py index cc1aa464..7d7b2300 100644 --- a/jsonargparse/_signatures.py +++ b/jsonargparse/_signatures.py @@ -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 @@ -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." @@ -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, diff --git a/jsonargparse/_stubs_resolver.py b/jsonargparse/_stubs_resolver.py index cef1f210..1ae774c4 100644 --- a/jsonargparse/_stubs_resolver.py +++ b/jsonargparse/_stubs_resolver.py @@ -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="", mode="exec"), exec_vars, exec_vars) diff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py index f19a0fe7..0201d818 100644 --- a/jsonargparse/_typehints.py +++ b/jsonargparse/_typehints.py @@ -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: diff --git a/jsonargparse/_util.py b/jsonargparse/_util.py index d0fec419..ec14337b 100644 --- a/jsonargparse/_util.py +++ b/jsonargparse/_util.py @@ -113,7 +113,7 @@ def capture_parser(function: Callable, *args, **kwargs) -> ArgumentParser: with parser_context(parser_capture=True): function(*args, **kwargs) except CaptureParserException as ex: - return ex.parser # type: ignore + return ex.parser # type: ignore[return-value] raise CaptureParserException(None) @@ -153,7 +153,7 @@ def parse_value_or_config( if isinstance(value, dict) and cfg_path is not None: value["__path__"] = cfg_path if nested_arg: - value = NestedArg(key=nested_arg.key, val=value) # type: ignore + value = NestedArg(key=nested_arg.key, val=value) # type: ignore[union-attr] return value, cfg_path @@ -407,12 +407,12 @@ def class_from_function( def __new__(cls, *args, **kwargs): return func(*args, **kwargs) - class ClassFromFunction(func_return, ClassFromFunctionBase): # type: ignore + class ClassFromFunction(func_return, ClassFromFunctionBase): # type: ignore[valid-type,misc] pass setattr(caller_module, name, ClassFromFunction) ClassFromFunction.wrapped_function = func - ClassFromFunction.__new__ = __new__ # type: ignore + ClassFromFunction.__new__ = __new__ # type: ignore[method-assign] ClassFromFunction.__doc__ = func.__doc__ ClassFromFunction.__module__ = caller_module.__name__ ClassFromFunction.__name__ = name @@ -742,7 +742,7 @@ class LoggerProperty: def __init__(self, *args, logger: Union[bool, str, dict, logging.Logger] = False, **kwargs): """Initializer for LoggerProperty class.""" - self.logger = logger # type: ignore + self.logger = logger # type: ignore[assignment] super().__init__(*args, **kwargs) @property diff --git a/jsonargparse/typing.py b/jsonargparse/typing.py index 3ccbf256..f252d09a 100644 --- a/jsonargparse/typing.py +++ b/jsonargparse/typing.py @@ -344,8 +344,8 @@ def add_type(type_class: Type, uniqueness_key: Optional[Tuple], type_check: Opti globals()[type_class.__name__] = type_class kwargs = {"uniqueness_key": uniqueness_key} if type_check is not None: - kwargs["type_check"] = type_check # type: ignore - register_type(type_class, type_class._type, **kwargs) # type: ignore + kwargs["type_check"] = type_check # type: ignore[assignment] + register_type(type_class, type_class._type, **kwargs) # type: ignore[arg-type] _fail_already_registered = False diff --git a/jsonargparse_tests/test_dataclass_like.py b/jsonargparse_tests/test_dataclass_like.py index 42b8ac7d..df8b4318 100644 --- a/jsonargparse_tests/test_dataclass_like.py +++ b/jsonargparse_tests/test_dataclass_like.py @@ -39,7 +39,7 @@ class DataClassA: a2: a2 help """ - a1: PositiveInt = PositiveInt(1) # type: ignore + a1: PositiveInt = PositiveInt(1) # type: ignore[valid-type] a2: str = "2" @@ -52,7 +52,7 @@ class DataClassB: b2: b2 help """ - b1: PositiveFloat = PositiveFloat(3.0) # type: ignore + b1: PositiveFloat = PositiveFloat(3.0) # type: ignore[valid-type] b2: DataClassA = DataClassA() @@ -490,7 +490,7 @@ class PydanticHelp(pydantic.BaseModel): if annotated and pydantic_support > 1: class PydanticAnnotatedField(pydantic.BaseModel): - p1: annotated[int, pydantic.Field(default=2, ge=1, le=8)] # type: ignore + p1: annotated[int, pydantic.Field(default=2, ge=1, le=8)] # type: ignore[valid-type] def none(x): diff --git a/jsonargparse_tests/test_parameter_resolvers.py b/jsonargparse_tests/test_parameter_resolvers.py index 66257fd1..92ec6f0e 100644 --- a/jsonargparse_tests/test_parameter_resolvers.py +++ b/jsonargparse_tests/test_parameter_resolvers.py @@ -372,8 +372,8 @@ def __init__( cal2: Calendar = calendar.TextCalendar(2), opt1: Callable[[List[int]], Optimizer] = lambda p: SGD(p, lr=0.01), opt2: Callable[[List[int]], Optimizer] = lambda p: SGD(p, 0.02), - opt3: Callable[[List[int]], Optimizer] = lambda p, lr=0.1: SGD(p, lr=lr), # type: ignore - opt4: Callable[[List[int]], Optimizer] = lambda p: Calendar(firstweekday=3), # type: ignore + opt3: Callable[[List[int]], Optimizer] = lambda p, lr=0.1: SGD(p, lr=lr), # type: ignore[misc] + opt4: Callable[[List[int]], Optimizer] = lambda p: Calendar(firstweekday=3), # type: ignore[assignment,return-value] **kwargs, ): """ diff --git a/jsonargparse_tests/test_postponed_annotations.py b/jsonargparse_tests/test_postponed_annotations.py index f729c15a..0d6b6baf 100644 --- a/jsonargparse_tests/test_postponed_annotations.py +++ b/jsonargparse_tests/test_postponed_annotations.py @@ -318,7 +318,7 @@ def test_get_types_dataclass_pep585(parser): @dataclasses.dataclass class DataWithInit585(Data585): - def __init__(self, b: Path_drw, **kwargs): # type: ignore + def __init__(self, b: Path_drw, **kwargs): # type: ignore[valid-type] super().__init__(b=os.fspath(b), **kwargs) diff --git a/jsonargparse_tests/test_signatures.py b/jsonargparse_tests/test_signatures.py index a9f140e8..6b051be4 100644 --- a/jsonargparse_tests/test_signatures.py +++ b/jsonargparse_tests/test_signatures.py @@ -229,8 +229,8 @@ def test_add_class_without_valid_parameters(parser): class WithNew: def __new__(cls, a1: int = 1, a2: float = 2.3): obj = object.__new__(cls) - obj.a1 = a1 # type: ignore - obj.a2 = a2 # type: ignore + obj.a1 = a1 # type: ignore[attr-defined] + obj.a2 = a2 # type: ignore[attr-defined] return obj @@ -559,7 +559,7 @@ def test_add_function_invalid_type(parser): ctx.match("all mandatory parameters must have a supported type") -def func_implicit_optional(a1: int = None): # type: ignore +def func_implicit_optional(a1: int = None): # type: ignore[assignment] return a1 diff --git a/jsonargparse_tests/test_typehints.py b/jsonargparse_tests/test_typehints.py index fd714a0f..17182a76 100644 --- a/jsonargparse_tests/test_typehints.py +++ b/jsonargparse_tests/test_typehints.py @@ -867,13 +867,13 @@ def test_action_typehint_none_type_error(): [ (Optional[bool], bool, True), (Union[type(None), bool], bool, True), - (Dict[bool, type(None)], bool, False), # type: ignore + (Dict[bool, type(None)], bool, False), # type: ignore[misc] (Optional[Path_fr], Path_fr, True), (Union[type(None), Path_fr], Path_fr, True), - (Dict[Path_fr, type(None)], Path_fr, False), # type: ignore + (Dict[Path_fr, type(None)], Path_fr, False), # type: ignore[misc,valid-type] (Optional[EnumABC], Enum, True), (Union[type(None), EnumABC], Enum, True), - (Dict[EnumABC, type(None)], Enum, False), # type: ignore + (Dict[EnumABC, type(None)], Enum, False), # type: ignore[misc] ], ids=str, ) diff --git a/jsonargparse_tests/test_util.py b/jsonargparse_tests/test_util.py index 88d227d1..14c93269 100644 --- a/jsonargparse_tests/test_util.py +++ b/jsonargparse_tests/test_util.py @@ -625,8 +625,8 @@ def test_class_from_function_given_return_type(): def get_calendar(a1: str, a2: int = 2) -> Calendar: """Returns instance of Calendar""" cal = Calendar() - cal.a1 = a1 # type: ignore - cal.a2 = a2 # type: ignore + cal.a1 = a1 # type: ignore[attr-defined] + cal.a2 = a2 # type: ignore[attr-defined] return cal