Skip to content

Commit bdd1556

Browse files
committed
Internal copy of GitHub PR #1237.
pyupgrade --py37-plus **/*.py Python f-strings are shorter, easier to read, and faster. https://www.scivision.dev/python-f-string-speed This PR touches both internal and external files, so I merged it directly, but we also need to import it so that the internal changes aren't reverted the next time we do an export. PiperOrigin-RevId: 457566465
1 parent fe5ef06 commit bdd1556

File tree

113 files changed

+451
-478
lines changed

Some content is hidden

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

113 files changed

+451
-478
lines changed

pytype/abstract/_base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,6 @@ def _compute_template(val: Any):
456456
template.extend(mro.MergeSequences(seqs))
457457
except ValueError as e:
458458
raise abstract_utils.GenericTypeError(
459-
val, "Illegal type parameter order in class %s" % val.name) from e
459+
val, f"Illegal type parameter order in class {val.name}") from e
460460

461461
return template

pytype/abstract/_classes.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def type_param_check(self):
160160
for t in self.template:
161161
if t.full_name in self.all_formal_type_parameters:
162162
raise abstract_utils.GenericTypeError(
163-
self, "Conflicting value for TypeVar %s" % t.full_name)
163+
self, f"Conflicting value for TypeVar {t.full_name}")
164164

165165
def collect_inner_cls_types(self, max_depth=5):
166166
"""Collect all the type parameters from nested classes."""
@@ -242,7 +242,7 @@ def _convert_slots(self, slots_var):
242242
for s in names:
243243
if not isinstance(s, str):
244244
self.ctx.errorlog.bad_slots(self.ctx.vm.frames,
245-
"Invalid __slot__ entry: %r" % str(s))
245+
f"Invalid __slot__ entry: {str(s)!r}")
246246
return None
247247
return tuple(self._mangle(s) for s in names)
248248

@@ -272,7 +272,7 @@ def instantiate(self, node, container=None):
272272
return super().instantiate(node, container)
273273

274274
def __repr__(self):
275-
return "InterpreterClass(%s)" % self.name
275+
return f"InterpreterClass({self.name})"
276276

277277
def __contains__(self, name):
278278
if name in self.members:
@@ -459,7 +459,7 @@ def _convert_member(self, name, member, subst=None):
459459
elif isinstance(member, pytd.Class):
460460
return self.ctx.convert.constant_to_var(member, subst=subst, node=node)
461461
else:
462-
raise AssertionError("Invalid class member %s" % pytd_utils.Print(member))
462+
raise AssertionError(f"Invalid class member {pytd_utils.Print(member)}")
463463

464464
def _new_instance(self, container, node, args):
465465
if self.full_name == "builtins.tuple" and args.is_empty():
@@ -478,7 +478,7 @@ def instantiate(self, node, container=None):
478478
abstract_utils.AsInstance(self.pytd_cls), {}, node)
479479

480480
def __repr__(self):
481-
return "PyTDClass(%s)" % self.name
481+
return f"PyTDClass({self.name})"
482482

483483
def __contains__(self, name):
484484
return name in self._member_map
@@ -593,7 +593,7 @@ def __init__(self, base_cls, formal_type_parameters, ctx, template=None):
593593
self.type_param_check()
594594

595595
def __repr__(self):
596-
return "ParameterizedClass(cls=%r params=%s)" % (
596+
return "ParameterizedClass(cls={!r} params={})".format(
597597
self.base_cls,
598598
self._formal_type_parameters)
599599

@@ -787,7 +787,7 @@ def __init__(self, base_cls, formal_type_parameters, ctx, template=None):
787787
self.num_args = len(self.formal_type_parameters) - 2
788788

789789
def __repr__(self):
790-
return "CallableClass(%s)" % self.formal_type_parameters
790+
return f"CallableClass({self.formal_type_parameters})"
791791

792792
def get_formal_type_parameters(self):
793793
return {
@@ -848,7 +848,7 @@ def __init__(self, instance, ctx, template=None):
848848
self._instance = instance
849849

850850
def __repr__(self):
851-
return "LiteralClass(%s)" % self._instance
851+
return f"LiteralClass({self._instance})"
852852

853853
def __eq__(self, other):
854854
if isinstance(other, LiteralClass):
@@ -895,7 +895,7 @@ def __init__(self, base_cls, formal_type_parameters, ctx, template=None):
895895
self.slots = () # tuples don't have any writable attributes
896896

897897
def __repr__(self):
898-
return "TupleClass(%s)" % self.formal_type_parameters
898+
return f"TupleClass({self.formal_type_parameters})"
899899

900900
def compute_mro(self):
901901
# ParameterizedClass removes the base PyTDClass(tuple) from the mro; add it

pytype/abstract/_function_base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def _match_views(self, node, args, alias_map, match_all_views):
134134
else:
135135
# Add the name of the caller if possible.
136136
if hasattr(self, "parent"):
137-
e.name = "%s.%s" % (self.parent.name, e.name)
137+
e.name = f"{self.parent.name}.{e.name}"
138138
if match_all_views or self.ctx.options.strict_parameter_checks:
139139
raise e
140140
error = e
@@ -344,7 +344,7 @@ def call(self, node, func, args, alias_map=None):
344344
# match_args will try to prepend the parent's name to the error name.
345345
# Overwrite it with _callself instead, which may be more exact.
346346
_, _, e.name = e.name.rpartition(".")
347-
e.name = "%s.%s" % (self._callself.data[0].name, e.name)
347+
e.name = f"{self._callself.data[0].name}.{e.name}"
348348
raise
349349
finally:
350350
if abstract_utils.func_name_is_class_init(self.name):
@@ -505,4 +505,4 @@ def __init__(self, ctx, iterable):
505505
self.iterable = iterable
506506

507507
def __repr__(self):
508-
return "splat(%r)" % self.iterable.data
508+
return f"splat({self.iterable.data!r})"

pytype/abstract/_instance_base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def argcount(self, node):
123123
return 0
124124

125125
def __repr__(self):
126-
return "<%s [%r]>" % (self.name, self.cls)
126+
return f"<{self.name} [{self.cls!r}]>"
127127

128128
def _get_class(self):
129129
return self.ctx.convert.unsolvable

pytype/abstract/_instances.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ def str_of_constant(self, printer):
269269
for val in self.pyval)
270270
if self.tuple_length == 1:
271271
content += ","
272-
return "(%s)" % content
272+
return f"({content})"
273273

274274
def _unique_parameters(self):
275275
parameters = super()._unique_parameters()

pytype/abstract/_pytd_function.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -444,7 +444,7 @@ def _match_args_sequentially(self, node, args, alias_map, match_all_views):
444444
if e > error:
445445
# Add the name of the caller if possible.
446446
if hasattr(self, "parent"):
447-
e.name = "%s.%s" % (self.parent.name, e.name)
447+
e.name = f"{self.parent.name}.{e.name}"
448448
error = e
449449
else:
450450
matched_signatures.append((sig, arg_dict, subst))
@@ -729,8 +729,7 @@ def _collect_mutated_parameters(cls, typ, mutated_type):
729729
not isinstance(mutated_type, pytd.GenericType) or
730730
typ.base_type != mutated_type.base_type or
731731
not isinstance(typ.base_type, pytd.ClassType)):
732-
raise ValueError("Unsupported mutation:\n%r ->\n%r" %
733-
(typ, mutated_type))
732+
raise ValueError(f"Unsupported mutation:\n{typ!r} ->\n{mutated_type!r}")
734733
return [zip(mutated_type.base_type.cls.template, mutated_type.parameters)]
735734

736735
def _get_mutation(self, node, arg_dict, subst, retvar, variable):

pytype/abstract/_typing.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def _build_value(self, node, inner, ellipses):
6363
raise NotImplementedError(self.__class__.__name__)
6464

6565
def __repr__(self):
66-
return "AnnotationClass(%s)" % self.name
66+
return f"AnnotationClass({self.name})"
6767

6868
def _get_class(self):
6969
return self.ctx.convert.type_type
@@ -77,7 +77,7 @@ def __init__(self, name, ctx, base_cls):
7777
self.base_cls = base_cls
7878

7979
def __repr__(self):
80-
return "AnnotationContainer(%s)" % self.name
80+
return f"AnnotationContainer({self.name})"
8181

8282
def _sub_annotation(
8383
self, annot: _base.BaseValue, subst: Mapping[str, _base.BaseValue]
@@ -244,7 +244,7 @@ def _build_value(self, node, inner, ellipses):
244244
for k, v in imports.items():
245245
added_imports[k] |= v
246246

247-
expr = "%s[%s]" % (self.base_cls.expr, ", ".join(printed_params))
247+
expr = f"{self.base_cls.expr}[{', '.join(printed_params)}]"
248248
annot = LateAnnotation(expr, self.base_cls.stack, self.ctx,
249249
imports=added_imports)
250250
self.ctx.vm.late_annotations[self.base_cls.expr].append(annot)
@@ -365,8 +365,8 @@ def __hash__(self):
365365
self.contravariant))
366366

367367
def __repr__(self):
368-
return "TypeParameter(%r, constraints=%r, bound=%r, module=%r)" % (
369-
self.name, self.constraints, self.bound, self.module)
368+
return ("TypeParameter({!r}, constraints={!r}, bound={!r}, module={!r})"
369+
.format(self.name, self.constraints, self.bound, self.module))
370370

371371
def instantiate(self, node, container=None):
372372
var = self.ctx.program.NewVariable()
@@ -385,8 +385,8 @@ def instantiate(self, node, container=None):
385385

386386
def update_official_name(self, name):
387387
if self.name != name:
388-
message = "TypeVar(%r) must be stored as %r, not %r" % (
389-
self.name, self.name, name)
388+
message = (f"TypeVar({self.name!r}) must be stored as {self.name!r}, "
389+
f"not {name!r}")
390390
self.ctx.errorlog.invalid_typevar(self.ctx.vm.frames, message)
391391

392392
def call(self, node, func, args, alias_map=None):
@@ -410,7 +410,7 @@ def call(self, node, func, args, alias_map=None):
410410
return node, self.ctx.convert.empty.to_variable(self.ctx.root_node)
411411

412412
def __repr__(self):
413-
return "TypeParameterInstance(%r)" % self.name
413+
return f"TypeParameterInstance({self.name!r})"
414414

415415
def __eq__(self, other):
416416
if isinstance(other, type(self)):
@@ -448,7 +448,7 @@ def __repr__(self):
448448
self._printing = True
449449
printed_contents = ", ".join(repr(o) for o in self.options)
450450
self._printing = False
451-
return "%s[%s]" % (self.name, printed_contents)
451+
return f"{self.name}[{printed_contents}]"
452452

453453
def __eq__(self, other):
454454
if isinstance(other, type(self)):
@@ -596,7 +596,7 @@ def unflatten_expr(self):
596596
return self.expr
597597

598598
def __repr__(self):
599-
return "LateAnnotation(%r, resolved=%r)" % (
599+
return "LateAnnotation({!r}, resolved={!r})".format(
600600
self.expr, self._type if self.resolved else None)
601601

602602
# __hash__ and __eq__ need to be explicitly defined for Python to use them in

pytype/abstract/abstract_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def _merge_type(t0, t1, name, cls):
306306
# t1 is a base of t0
307307
if t1 in t0.mro:
308308
return t0
309-
raise GenericTypeError(cls, "Conflicting value for TypeVar %s" % name)
309+
raise GenericTypeError(cls, f"Conflicting value for TypeVar {name}")
310310

311311

312312
def parse_formal_type_parameters(

pytype/abstract/class_mixin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,7 @@ def _call_method(self, node, value, method_name, args):
417417
node, method = self.ctx.attribute_handler.get_attribute(
418418
node, value.data, method_name, value)
419419
if method:
420-
call_repr = "%s.%s(..._)" % (self.name, method_name)
420+
call_repr = f"{self.name}.{method_name}(..._)"
421421
log.debug("calling %s", call_repr)
422422
node, ret = function.call_function(self.ctx, node, method, args)
423423
log.debug("%s returned %r", call_repr, ret)

pytype/abstract/function.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -372,8 +372,7 @@ def _print_default(self, name):
372372
def __repr__(self):
373373
args = ", ".join(self._yield_arguments())
374374
ret = self._print_annot("return")
375-
return "def {name}({args}) -> {ret}".format(
376-
name=self.name, args=args, ret=ret if ret else "Any")
375+
return f"def {self.name}({args}) -> {ret if ret else 'Any'}"
377376

378377
def get_first_arg(self, callargs):
379378
return callargs.get(self.param_names[0]) if self.param_names else None
@@ -902,8 +901,8 @@ def match_all_args(ctx, node, func, args):
902901
break
903902
else:
904903
raise AssertionError(
905-
"Mismatched parameter %s not found in passed_args" %
906-
arg_name) from e
904+
f"Mismatched parameter {arg_name} not found in passed_args"
905+
) from e
907906
else:
908907
# This is not an InvalidParameters error.
909908
raise

0 commit comments

Comments
 (0)