Skip to content

Commit 917aa83

Browse files
author
hauntsaninja
committed
mypy: run pyupgrade
Re-attempt of #10741 Ran: `pyupgrade --py36-plus $(fd -e py) --keep-runtime-typing` I mostly only needed to change things where NamedTuple comments got dropped. Notably, I omitted changes to pyinfo.py
1 parent ce6d243 commit 917aa83

Some content is hidden

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

67 files changed

+710
-718
lines changed

mypy/binder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def update_from_options(self, frames: List[Frame]) -> bool:
189189

190190
frames = [f for f in frames if not f.unreachable]
191191
changed = False
192-
keys = set(key for f in frames for key in f.types)
192+
keys = {key for f in frames for key in f.types}
193193

194194
for key in keys:
195195
current_value = self._get(key)

mypy/build.py

Lines changed: 76 additions & 76 deletions
Large diffs are not rendered by default.

mypy/checker.py

Lines changed: 32 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -97,26 +97,23 @@
9797
DeferredNodeType: _TypeAlias = Union[FuncDef, LambdaExpr, OverloadedFuncDef, Decorator]
9898
FineGrainedDeferredNodeType: _TypeAlias = Union[FuncDef, MypyFile, OverloadedFuncDef]
9999

100+
100101
# A node which is postponed to be processed during the next pass.
101102
# In normal mode one can defer functions and methods (also decorated and/or overloaded)
102103
# and lambda expressions. Nested functions can't be deferred -- only top-level functions
103104
# and methods of classes not defined within a function can be deferred.
104-
DeferredNode = NamedTuple(
105-
'DeferredNode',
106-
[
107-
('node', DeferredNodeType),
108-
('active_typeinfo', Optional[TypeInfo]), # And its TypeInfo (for semantic analysis
109-
# self type handling)
110-
])
105+
class DeferredNode(NamedTuple):
106+
node: DeferredNodeType
107+
# And its TypeInfo (for semantic analysis self type handling
108+
active_typeinfo: Optional[TypeInfo]
109+
111110

112111
# Same as above, but for fine-grained mode targets. Only top-level functions/methods
113112
# and module top levels are allowed as such.
114-
FineGrainedDeferredNode = NamedTuple(
115-
'FineGrainedDeferredNode',
116-
[
117-
('node', FineGrainedDeferredNodeType),
118-
('active_typeinfo', Optional[TypeInfo]),
119-
])
113+
class FineGrainedDeferredNode(NamedTuple):
114+
node: FineGrainedDeferredNodeType
115+
active_typeinfo: Optional[TypeInfo]
116+
120117

121118
# Data structure returned by find_isinstance_check representing
122119
# information learned from the truth or falsehood of a condition. The
@@ -131,25 +128,23 @@
131128
# (such as two references to the same variable). TODO: it would
132129
# probably be better to have the dict keyed by the nodes' literal_hash
133130
# field instead.
134-
135131
TypeMap: _TypeAlias = Optional[Dict[Expression, Type]]
136132

133+
137134
# An object that represents either a precise type or a type with an upper bound;
138135
# it is important for correct type inference with isinstance.
139-
TypeRange = NamedTuple(
140-
'TypeRange',
141-
[
142-
('item', Type),
143-
('is_upper_bound', bool), # False => precise type
144-
])
136+
class TypeRange(NamedTuple):
137+
item: Type
138+
is_upper_bound: bool # False => precise type
139+
145140

146141
# Keeps track of partial types in a single scope. In fine-grained incremental
147142
# mode partial types initially defined at the top level cannot be completed in
148143
# a function, and we use the 'is_function' attribute to enforce this.
149-
PartialTypeScope = NamedTuple('PartialTypeScope', [('map', Dict[Var, Context]),
150-
('is_function', bool),
151-
('is_local', bool),
152-
])
144+
class PartialTypeScope(NamedTuple):
145+
map: Dict[Var, Context]
146+
is_function: bool
147+
is_local: bool
153148

154149

155150
class TypeChecker(NodeVisitor[None], CheckerPluginInterface):
@@ -891,7 +886,7 @@ def check_func_def(self, defn: FuncItem, typ: CallableType, name: Optional[str])
891886
self.msg.unimported_type_becomes_any("Return type", ret_type, fdef)
892887
for idx, arg_type in enumerate(fdef.type.arg_types):
893888
if has_any_from_unimported_type(arg_type):
894-
prefix = "Argument {} to \"{}\"".format(idx + 1, fdef.name)
889+
prefix = f"Argument {idx + 1} to \"{fdef.name}\""
895890
self.msg.unimported_type_becomes_any(prefix, arg_type, fdef)
896891
check_for_explicit_any(fdef.type, self.options, self.is_typeshed_stub,
897892
self.msg, context=fdef)
@@ -1062,9 +1057,9 @@ def check_default_args(self, item: FuncItem, body_is_trivial: bool) -> None:
10621057
name = arg.variable.name
10631058
msg = 'Incompatible default for '
10641059
if name.startswith('__tuple_arg_'):
1065-
msg += "tuple argument {}".format(name[12:])
1060+
msg += f"tuple argument {name[12:]}"
10661061
else:
1067-
msg += 'argument "{}"'.format(name)
1062+
msg += f'argument "{name}"'
10681063
self.check_simple_assignment(
10691064
arg.variable.type,
10701065
arg.initializer,
@@ -1964,7 +1959,7 @@ def check_enum_bases(self, defn: ClassDef) -> None:
19641959
continue
19651960
elif enum_base is not None:
19661961
self.fail(
1967-
'No base classes are allowed after "{}"'.format(enum_base),
1962+
f'No base classes are allowed after "{enum_base}"',
19681963
defn,
19691964
)
19701965
break
@@ -3308,8 +3303,8 @@ def check_simple_assignment(self, lvalue_type: Optional[Type], rvalue: Expressio
33083303
self.msg.deleted_as_lvalue(lvalue_type, context)
33093304
elif lvalue_type:
33103305
self.check_subtype(rvalue_type, lvalue_type, context, msg,
3311-
'{} has type'.format(rvalue_name),
3312-
'{} has type'.format(lvalue_name), code=code)
3306+
f'{rvalue_name} has type',
3307+
f'{lvalue_name} has type', code=code)
33133308
return rvalue_type
33143309

33153310
def check_member_assignment(self, instance_type: Type, attribute_type: Type,
@@ -3717,7 +3712,7 @@ def _type_check_raise_python2(self, e: Expression, s: RaiseStmt, typ: ProperType
37173712
expected_type = TypeType(exc_type)
37183713
self.check_subtype(
37193714
typ.items[0], expected_type, s,
3720-
'Argument 1 must be "{}" subtype'.format(expected_type),
3715+
f'Argument 1 must be "{expected_type}" subtype',
37213716
)
37223717

37233718
# Typecheck `traceback` part:
@@ -3732,7 +3727,7 @@ def _type_check_raise_python2(self, e: Expression, s: RaiseStmt, typ: ProperType
37323727
])
37333728
self.check_subtype(
37343729
typ.items[2], traceback_type, s,
3735-
'Argument 3 must be "{}" subtype'.format(traceback_type),
3730+
f'Argument 3 must be "{traceback_type}" subtype',
37363731
)
37373732
else:
37383733
expected_type_items = [
@@ -4302,7 +4297,7 @@ def _make_fake_typeinfo_and_full_name(
43024297
curr_module_: MypyFile,
43034298
) -> Tuple[TypeInfo, str]:
43044299
names_list = pretty_seq([x.type.name for x in base_classes_], "and")
4305-
short_name = '<subclass of {}>'.format(names_list)
4300+
short_name = f'<subclass of {names_list}>'
43064301
full_name_ = gen_unique_name(short_name, curr_module_.names)
43074302
cdef, info_ = self.make_fake_typeinfo(
43084303
curr_module_.fullname,
@@ -4354,7 +4349,7 @@ def intersect_instance_callable(self, typ: Instance, callable_type: CallableType
43544349
# have a valid fullname and a corresponding entry in a symbol table. We generate
43554350
# a unique name inside the symbol table of the current module.
43564351
cur_module = cast(MypyFile, self.scope.stack[0])
4357-
gen_name = gen_unique_name("<callable subtype of {}>".format(typ.type.name),
4352+
gen_name = gen_unique_name(f"<callable subtype of {typ.type.name}>",
43584353
cur_module.names)
43594354

43604355
# Synthesize a fake TypeInfo
@@ -5367,7 +5362,7 @@ def lookup(self, name: str) -> SymbolTableNode:
53675362
table = cast(MypyFile, b.node).names
53685363
if name in table:
53695364
return table[name]
5370-
raise KeyError('Failed lookup: {}'.format(name))
5365+
raise KeyError(f'Failed lookup: {name}')
53715366

53725367
def lookup_qualified(self, name: str) -> SymbolTableNode:
53735368
if '.' not in name:
@@ -5891,7 +5886,7 @@ def and_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
58915886
# arbitrarily give precedence to m2. (In the future, we could use
58925887
# an intersection type.)
58935888
result = m2.copy()
5894-
m2_keys = set(literal_hash(n2) for n2 in m2)
5889+
m2_keys = {literal_hash(n2) for n2 in m2}
58955890
for n1 in m1:
58965891
if literal_hash(n1) not in m2_keys:
58975892
result[n1] = m1[n1]
@@ -6561,7 +6556,7 @@ def is_static(func: Union[FuncBase, Decorator]) -> bool:
65616556
return is_static(func.func)
65626557
elif isinstance(func, FuncBase):
65636558
return func.is_static
6564-
assert False, "Unexpected func type: {}".format(type(func))
6559+
assert False, f"Unexpected func type: {type(func)}"
65656560

65666561

65676562
def is_subtype_no_promote(left: Type, right: Type) -> bool:

mypy/checkexpr.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def extract_refexpr_names(expr: RefExpr) -> Set[str]:
146146
else:
147147
break
148148
else:
149-
raise AssertionError("Unknown RefExpr subclass: {}".format(type(expr)))
149+
raise AssertionError(f"Unknown RefExpr subclass: {type(expr)}")
150150
return output
151151

152152

@@ -427,7 +427,7 @@ def method_fullname(self, object_type: Type, method_name: str) -> Optional[str]:
427427
type_name = tuple_fallback(object_type).type.fullname
428428

429429
if type_name is not None:
430-
return '{}.{}'.format(type_name, method_name)
430+
return f'{type_name}.{method_name}'
431431
else:
432432
return None
433433

@@ -582,7 +582,7 @@ def check_typeddict_call_with_kwargs(self, callee: TypedDictType,
582582
self.chk.check_simple_assignment(
583583
lvalue_type=item_expected_type, rvalue=item_value, context=item_value,
584584
msg=message_registry.INCOMPATIBLE_TYPES,
585-
lvalue_name='TypedDict item "{}"'.format(item_name),
585+
lvalue_name=f'TypedDict item "{item_name}"',
586586
rvalue_name='expression',
587587
code=codes.TYPEDDICT_ITEM)
588588

@@ -2188,7 +2188,7 @@ def visit_op_expr(self, e: OpExpr) -> Type:
21882188
e.method_type = method_type
21892189
return result
21902190
else:
2191-
raise RuntimeError('Unknown operator {}'.format(e.op))
2191+
raise RuntimeError(f'Unknown operator {e.op}')
21922192

21932193
def visit_comparison_expr(self, e: ComparisonExpr) -> Type:
21942194
"""Type check a comparison expression.
@@ -2285,7 +2285,7 @@ def visit_comparison_expr(self, e: ComparisonExpr) -> Type:
22852285
self.msg.dangerous_comparison(left_type, right_type, 'identity', e)
22862286
method_type = None
22872287
else:
2288-
raise RuntimeError('Unknown comparison operator {}'.format(operator))
2288+
raise RuntimeError(f'Unknown comparison operator {operator}')
22892289

22902290
e.method_types.append(method_type)
22912291

mypy/checkmember.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ def analyze_type_callable_member_access(name: str,
263263
# Look up from the 'type' type.
264264
return _analyze_member_access(name, typ.fallback, mx)
265265
else:
266-
assert False, 'Unexpected type {}'.format(repr(ret_type))
266+
assert False, f'Unexpected type {repr(ret_type)}'
267267

268268

269269
def analyze_type_type_member_access(name: str,
@@ -410,7 +410,7 @@ def analyze_member_var_access(name: str,
410410
result = getattr_type
411411

412412
# Call the attribute hook before returning.
413-
fullname = '{}.{}'.format(method.info.fullname, name)
413+
fullname = f'{method.info.fullname}.{name}'
414414
hook = mx.chk.plugin.get_attribute_hook(fullname)
415415
if hook:
416416
result = hook(AttributeContext(get_proper_type(mx.original_type),
@@ -607,7 +607,7 @@ def analyze_var(name: str,
607607
mx.not_ready_callback(var.name, mx.context)
608608
# Implicit 'Any' type.
609609
result = AnyType(TypeOfAny.special_form)
610-
fullname = '{}.{}'.format(var.info.fullname, name)
610+
fullname = f'{var.info.fullname}.{name}'
611611
hook = mx.chk.plugin.get_attribute_hook(fullname)
612612
if result and not mx.is_lvalue and not implicit:
613613
result = analyze_descriptor_access(result, mx)

mypy/checkpattern.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,13 +53,10 @@
5353
# For every Pattern a PatternType can be calculated. This requires recursively calculating
5454
# the PatternTypes of the sub-patterns first.
5555
# Using the data in the PatternType the match subject and captured names can be narrowed/inferred.
56-
PatternType = NamedTuple(
57-
'PatternType',
58-
[
59-
('type', Type), # The type the match subject can be narrowed to
60-
('rest_type', Type), # The remaining type if the pattern didn't match
61-
('captures', Dict[Expression, Type]), # The variables captured by the pattern
62-
])
56+
class PatternType(NamedTuple):
57+
type: Type # The type the match subject can be narrowed to
58+
rest_type: Type # The remaining type if the pattern didn't match
59+
captures: Dict[Expression, Type] # The variables captured by the pattern
6360

6461

6562
class PatternChecker(PatternVisitor[PatternType]):
@@ -628,7 +625,7 @@ def update_type_map(self,
628625
) -> None:
629626
# Calculating this would not be needed if TypeMap directly used literal hashes instead of
630627
# expressions, as suggested in the TODO above it's definition
631-
already_captured = set(literal_hash(expr) for expr in original_type_map)
628+
already_captured = {literal_hash(expr) for expr in original_type_map}
632629
for expr, typ in extra_type_map.items():
633630
if literal_hash(expr) in already_captured:
634631
node = get_var(expr)

mypy/checkstrformat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ def apply_field_accessors(self, spec: ConversionSpecifier, repl: Expression,
519519
dummy, fnam="<format>", module=None, options=self.chk.options, errors=temp_errors
520520
)
521521
if temp_errors.is_errors():
522-
self.msg.fail('Syntax error in format specifier "{}"'.format(spec.field),
522+
self.msg.fail(f'Syntax error in format specifier "{spec.field}"',
523523
ctx, code=codes.STRING_FORMATTING)
524524
return TempNode(AnyType(TypeOfAny.from_error))
525525

0 commit comments

Comments
 (0)