Skip to content

Commit d0d5876

Browse files
authored
Fix various lint (#16726)
1 parent 4aba5ca commit d0d5876

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+102
-93
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ repos:
1010
hooks:
1111
- id: black
1212
- repo: https://github.com/astral-sh/ruff-pre-commit
13-
rev: v0.1.0 # must match test-requirements.txt
13+
rev: v0.1.4 # must match test-requirements.txt
1414
hooks:
1515
- id: ruff
1616
args: [--exit-non-zero-on-fix]

mypy/binder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ def assign_type(
291291
self.type_assignments[expr].append((type, declared_type))
292292
return
293293
if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)):
294-
return None
294+
return
295295
if not literal(expr):
296296
return
297297
self.invalidate_dependencies(expr)

mypy/build.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -682,9 +682,7 @@ def __init__(
682682
# for efficient lookup
683683
self.shadow_map: dict[str, str] = {}
684684
if self.options.shadow_file is not None:
685-
self.shadow_map = {
686-
source_file: shadow_file for (source_file, shadow_file) in self.options.shadow_file
687-
}
685+
self.shadow_map = dict(self.options.shadow_file)
688686
# a mapping from each file being typechecked to its possible shadow file
689687
self.shadow_equivalence_map: dict[str, str | None] = {}
690688
self.plugin = plugin
@@ -1120,7 +1118,7 @@ def read_deps_cache(manager: BuildManager, graph: Graph) -> dict[str, FgDepMeta]
11201118
module_deps_metas = deps_meta["deps_meta"]
11211119
assert isinstance(module_deps_metas, dict)
11221120
if not manager.options.skip_cache_mtime_checks:
1123-
for id, meta in module_deps_metas.items():
1121+
for meta in module_deps_metas.values():
11241122
try:
11251123
matched = manager.getmtime(meta["path"]) == meta["mtime"]
11261124
except FileNotFoundError:
@@ -2093,7 +2091,7 @@ def load_tree(self, temporary: bool = False) -> None:
20932091
self.meta.data_json, self.manager, "Load tree ", "Could not load tree: "
20942092
)
20952093
if data is None:
2096-
return None
2094+
return
20972095

20982096
t0 = time.time()
20992097
# TODO: Assert data file wasn't changed.
@@ -3383,7 +3381,7 @@ def order_ascc(graph: Graph, ascc: AbstractSet[str], pri_max: int = PRI_ALL) ->
33833381
strongly_connected_components() below for a reference.
33843382
"""
33853383
if len(ascc) == 1:
3386-
return [s for s in ascc]
3384+
return list(ascc)
33873385
pri_spread = set()
33883386
for id in ascc:
33893387
state = graph[id]

mypy/checker.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -632,7 +632,7 @@ def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
632632
if not defn.items:
633633
# In this case we have already complained about none of these being
634634
# valid overloads.
635-
return None
635+
return
636636
if len(defn.items) == 1:
637637
self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, defn)
638638

@@ -676,7 +676,6 @@ def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
676676
self.msg.no_overridable_method(defn.name, defn)
677677
self.check_explicit_override_decorator(defn, found_method_base_classes, defn.impl)
678678
self.check_inplace_operator_method(defn)
679-
return None
680679

681680
def extract_callable_type(self, inner_type: Type | None, ctx: Context) -> CallableType | None:
682681
"""Get type as seen by an overload item caller."""
@@ -1838,7 +1837,7 @@ def check_match_args(self, var: Var, typ: Type, context: Context) -> None:
18381837
return
18391838
typ = get_proper_type(typ)
18401839
if not isinstance(typ, TupleType) or not all(
1841-
[is_string_literal(item) for item in typ.items]
1840+
is_string_literal(item) for item in typ.items
18421841
):
18431842
self.msg.note(
18441843
"__match_args__ must be a tuple containing string literals for checking "
@@ -5045,7 +5044,7 @@ def visit_break_stmt(self, s: BreakStmt) -> None:
50455044

50465045
def visit_continue_stmt(self, s: ContinueStmt) -> None:
50475046
self.binder.handle_continue()
5048-
return None
5047+
return
50495048

50505049
def visit_match_stmt(self, s: MatchStmt) -> None:
50515050
with self.binder.frame_context(can_skip=False, fall_through=0):

mypy/checkexpr.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,7 @@ def check_typeddict_call(
739739
context: Context,
740740
orig_callee: Type | None,
741741
) -> Type:
742-
if args and all([ak in (ARG_NAMED, ARG_STAR2) for ak in arg_kinds]):
742+
if args and all(ak in (ARG_NAMED, ARG_STAR2) for ak in arg_kinds):
743743
# ex: Point(x=42, y=1337, **extras)
744744
# This is a bit ugly, but this is a price for supporting all possible syntax
745745
# variants for TypedDict constructors.
@@ -4017,9 +4017,7 @@ def check_op(
40174017
left_variants = [base_type]
40184018
base_type = get_proper_type(base_type)
40194019
if isinstance(base_type, UnionType):
4020-
left_variants = [
4021-
item for item in flatten_nested_unions(base_type.relevant_items())
4022-
]
4020+
left_variants = list(flatten_nested_unions(base_type.relevant_items()))
40234021
right_type = self.accept(arg)
40244022

40254023
# Step 1: We first try leaving the right arguments alone and destructure

mypy/checkpattern.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ def visit_or_pattern(self, o: OrPattern) -> PatternType:
187187
capture_types[node].append((expr, typ))
188188

189189
captures: dict[Expression, Type] = {}
190-
for var, capture_list in capture_types.items():
190+
for capture_list in capture_types.values():
191191
typ = UninhabitedType()
192192
for _, other in capture_list:
193193
typ = join_types(typ, other)

mypy/checkstrformat.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,7 @@ def check_specs_in_format_call(
372372
):
373373
# TODO: add support for some custom specs like datetime?
374374
self.msg.fail(
375-
"Unrecognized format" ' specification "{}"'.format(spec.format_spec[1:]),
375+
f'Unrecognized format specification "{spec.format_spec[1:]}"',
376376
call,
377377
code=codes.STRING_FORMATTING,
378378
)
@@ -482,7 +482,7 @@ def find_replacements_in_call(self, call: CallExpr, keys: list[str]) -> list[Exp
482482
expr = self.get_expr_by_name(key, call)
483483
if not expr:
484484
self.msg.fail(
485-
"Cannot find replacement for named" ' format specifier "{}"'.format(key),
485+
f'Cannot find replacement for named format specifier "{key}"',
486486
call,
487487
code=codes.STRING_FORMATTING,
488488
)

mypy/dmypy_server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1055,7 +1055,7 @@ def fix_module_deps(graph: mypy.build.Graph) -> None:
10551055
This can make some suppressed dependencies non-suppressed, and vice versa (if modules
10561056
have been added to or removed from the build).
10571057
"""
1058-
for module, state in graph.items():
1058+
for state in graph.values():
10591059
new_suppressed = []
10601060
new_dependencies = []
10611061
for dep in state.dependencies + state.suppressed:

mypy/dmypy_util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def send(connection: IPCBase, data: Any) -> None:
4343
class WriteToConn:
4444
"""Helper class to write to a connection instead of standard output."""
4545

46-
def __init__(self, server: IPCBase, output_key: str = "stdout"):
46+
def __init__(self, server: IPCBase, output_key: str = "stdout") -> None:
4747
self.server = server
4848
self.output_key = output_key
4949

mypy/errors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ def __init__(
170170
*,
171171
filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,
172172
save_filtered_errors: bool = False,
173-
):
173+
) -> None:
174174
self.errors = errors
175175
self._has_new_errors = False
176176
self._filter = filter_errors

mypy/main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def main(
145145
sys.exit(code)
146146

147147
# HACK: keep res alive so that mypyc won't free it before the hard_exit
148-
list([res])
148+
list([res]) # noqa: C410
149149

150150

151151
def run_build(
@@ -349,7 +349,7 @@ class CapturableArgumentParser(argparse.ArgumentParser):
349349
yet output must be captured to properly support mypy.api.run.
350350
"""
351351

352-
def __init__(self, *args: Any, **kwargs: Any):
352+
def __init__(self, *args: Any, **kwargs: Any) -> None:
353353
self.stdout = kwargs.pop("stdout", sys.stdout)
354354
self.stderr = kwargs.pop("stderr", sys.stderr)
355355
super().__init__(*args, **kwargs)
@@ -415,7 +415,7 @@ def __init__(
415415
default: str = argparse.SUPPRESS,
416416
help: str = "show program's version number and exit",
417417
stdout: IO[str] | None = None,
418-
):
418+
) -> None:
419419
super().__init__(
420420
option_strings=option_strings, dest=dest, default=default, nargs=0, help=help
421421
)

mypy/message_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage:
5252
'"return" with value in async generator is not allowed'
5353
)
5454
INVALID_RETURN_TYPE_FOR_GENERATOR: Final = ErrorMessage(
55-
'The return type of a generator function should be "Generator"' " or one of its supertypes"
55+
'The return type of a generator function should be "Generator" or one of its supertypes'
5656
)
5757
INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR: Final = ErrorMessage(
5858
'The return type of an async generator function should be "AsyncGenerator" or one of its '

mypy/messages.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3099,7 +3099,7 @@ def append_invariance_notes(
30993099
):
31003100
invariant_type = "Dict"
31013101
covariant_suggestion = (
3102-
'Consider using "Mapping" instead, ' "which is covariant in the value type"
3102+
'Consider using "Mapping" instead, which is covariant in the value type'
31033103
)
31043104
if invariant_type and covariant_suggestion:
31053105
notes.append(

mypy/nodes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3137,7 +3137,7 @@ def protocol_members(self) -> list[str]:
31373137
if name in EXCLUDED_PROTOCOL_ATTRIBUTES:
31383138
continue
31393139
members.add(name)
3140-
return sorted(list(members))
3140+
return sorted(members)
31413141

31423142
def __getitem__(self, name: str) -> SymbolTableNode:
31433143
n = self.get(name)
@@ -3296,7 +3296,7 @@ def serialize(self) -> JsonDict:
32963296
else self.typeddict_type.serialize(),
32973297
"flags": get_flags(self, TypeInfo.FLAGS),
32983298
"metadata": self.metadata,
3299-
"slots": list(sorted(self.slots)) if self.slots is not None else None,
3299+
"slots": sorted(self.slots) if self.slots is not None else None,
33003300
"deletable_attributes": self.deletable_attributes,
33013301
"self_type": self.self_type.serialize() if self.self_type is not None else None,
33023302
"dataclass_transform_spec": (
@@ -3966,7 +3966,7 @@ def __init__(
39663966
# frozen_default was added to CPythonin https://github.com/python/cpython/pull/99958 citing
39673967
# positive discussion in typing-sig
39683968
frozen_default: bool | None = None,
3969-
):
3969+
) -> None:
39703970
self.eq_default = eq_default if eq_default is not None else True
39713971
self.order_default = order_default if order_default is not None else False
39723972
self.kw_only_default = kw_only_default if kw_only_default is not None else False

mypy/patterns.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class ValuePattern(Pattern):
6060

6161
expr: Expression
6262

63-
def __init__(self, expr: Expression):
63+
def __init__(self, expr: Expression) -> None:
6464
super().__init__()
6565
self.expr = expr
6666

@@ -72,7 +72,7 @@ class SingletonPattern(Pattern):
7272
# This can be exactly True, False or None
7373
value: bool | None
7474

75-
def __init__(self, value: bool | None):
75+
def __init__(self, value: bool | None) -> None:
7676
super().__init__()
7777
self.value = value
7878

@@ -85,7 +85,7 @@ class SequencePattern(Pattern):
8585

8686
patterns: list[Pattern]
8787

88-
def __init__(self, patterns: list[Pattern]):
88+
def __init__(self, patterns: list[Pattern]) -> None:
8989
super().__init__()
9090
self.patterns = patterns
9191

@@ -98,7 +98,7 @@ class StarredPattern(Pattern):
9898
# a name.
9999
capture: NameExpr | None
100100

101-
def __init__(self, capture: NameExpr | None):
101+
def __init__(self, capture: NameExpr | None) -> None:
102102
super().__init__()
103103
self.capture = capture
104104

@@ -111,7 +111,9 @@ class MappingPattern(Pattern):
111111
values: list[Pattern]
112112
rest: NameExpr | None
113113

114-
def __init__(self, keys: list[Expression], values: list[Pattern], rest: NameExpr | None):
114+
def __init__(
115+
self, keys: list[Expression], values: list[Pattern], rest: NameExpr | None
116+
) -> None:
115117
super().__init__()
116118
assert len(keys) == len(values)
117119
self.keys = keys
@@ -136,7 +138,7 @@ def __init__(
136138
positionals: list[Pattern],
137139
keyword_keys: list[str],
138140
keyword_values: list[Pattern],
139-
):
141+
) -> None:
140142
super().__init__()
141143
assert len(keyword_keys) == len(keyword_values)
142144
self.class_ref = class_ref

mypy/plugins/enums.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,11 +166,11 @@ class SomeEnum:
166166
for n in stnodes
167167
if n is None or not n.implicit
168168
)
169-
proper_types = list(
169+
proper_types = [
170170
_infer_value_type_with_auto_fallback(ctx, t)
171171
for t in node_types
172172
if t is None or not isinstance(t, CallableType)
173-
)
173+
]
174174
underlying_type = _first(proper_types)
175175
if underlying_type is None:
176176
return ctx.default_attr_type

mypy/renaming.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ def flush_refs(self) -> None:
270270
This will be called at the end of a scope.
271271
"""
272272
is_func = self.scope_kinds[-1] == FUNCTION
273-
for name, refs in self.refs[-1].items():
273+
for refs in self.refs[-1].values():
274274
if len(refs) == 1:
275275
# Only one definition -- no renaming needed.
276276
continue

mypy/semanal.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4153,7 +4153,7 @@ def check_typevarlike_name(self, call: CallExpr, name: str, context: Context) ->
41534153
if len(call.args) < 1:
41544154
self.fail(f"Too few arguments for {typevarlike_type}()", context)
41554155
return False
4156-
if not isinstance(call.args[0], StrExpr) or not call.arg_kinds[0] == ARG_POS:
4156+
if not isinstance(call.args[0], StrExpr) or call.arg_kinds[0] != ARG_POS:
41574157
self.fail(f"{typevarlike_type}() expects a string literal as first argument", context)
41584158
return False
41594159
elif call.args[0].value != name:
@@ -4961,9 +4961,7 @@ def visit_name_expr(self, expr: NameExpr) -> None:
49614961
def bind_name_expr(self, expr: NameExpr, sym: SymbolTableNode) -> None:
49624962
"""Bind name expression to a symbol table node."""
49634963
if isinstance(sym.node, TypeVarExpr) and self.tvar_scope.get_binding(sym):
4964-
self.fail(
4965-
'"{}" is a type variable and only valid in type ' "context".format(expr.name), expr
4966-
)
4964+
self.fail(f'"{expr.name}" is a type variable and only valid in type context', expr)
49674965
elif isinstance(sym.node, PlaceholderNode):
49684966
self.process_placeholder(expr.name, "name", expr)
49694967
else:
@@ -6809,13 +6807,13 @@ def parse_dataclass_transform_spec(self, call: CallExpr) -> DataclassTransformSp
68096807
def parse_dataclass_transform_field_specifiers(self, arg: Expression) -> tuple[str, ...]:
68106808
if not isinstance(arg, TupleExpr):
68116809
self.fail('"field_specifiers" argument must be a tuple literal', arg)
6812-
return tuple()
6810+
return ()
68136811

68146812
names = []
68156813
for specifier in arg.items:
68166814
if not isinstance(specifier, RefExpr):
68176815
self.fail('"field_specifiers" must only contain identifiers', specifier)
6818-
return tuple()
6816+
return ()
68196817
names.append(specifier.fullname)
68206818
return tuple(names)
68216819

mypy/semanal_enum.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def parse_enum_call_args(
148148
Return a tuple of fields, values, was there an error.
149149
"""
150150
args = call.args
151-
if not all([arg_kind in [ARG_POS, ARG_NAMED] for arg_kind in call.arg_kinds]):
151+
if not all(arg_kind in [ARG_POS, ARG_NAMED] for arg_kind in call.arg_kinds):
152152
return self.fail_enum_call_arg(f"Unexpected arguments to {class_name}()", call)
153153
if len(args) < 2:
154154
return self.fail_enum_call_arg(f"Too few arguments for {class_name}()", call)

mypy/semanal_namedtuple.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@
8585
)
8686

8787
NAMEDTUP_CLASS_ERROR: Final = (
88-
"Invalid statement in NamedTuple definition; " 'expected "field_name: field_type [= default]"'
88+
'Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"'
8989
)
9090

9191
SELF_TVAR_NAME: Final = "_NT"

mypy/semanal_typeddict.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
)
5151

5252
TPDICT_CLASS_ERROR: Final = (
53-
"Invalid statement in TypedDict definition; " 'expected "field_name: field_type"'
53+
'Invalid statement in TypedDict definition; expected "field_name: field_type"'
5454
)
5555

5656

mypy/server/astmerge.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ def process_synthetic_type_info(self, info: TypeInfo) -> None:
394394
# have bodies in the AST so we need to iterate over their symbol
395395
# tables separately, unlike normal classes.
396396
self.process_type_info(info)
397-
for name, node in info.names.items():
397+
for node in info.names.values():
398398
if node.node:
399399
node.node.accept(self)
400400

@@ -549,7 +549,7 @@ def fixup(self, node: SN) -> SN:
549549
def replace_nodes_in_symbol_table(
550550
symbols: SymbolTable, replacements: dict[SymbolNode, SymbolNode]
551551
) -> None:
552-
for name, node in symbols.items():
552+
for node in symbols.values():
553553
if node.node:
554554
if node.node in replacements:
555555
new = replacements[node.node]

0 commit comments

Comments
 (0)