diff options
| author | Daniël van Noord <13665637+DanielNoord@users.noreply.github.com> | 2021-09-17 13:46:25 +0200 |
|---|---|---|
| committer | Daniël van Noord <13665637+DanielNoord@users.noreply.github.com> | 2021-09-17 14:52:36 +0200 |
| commit | e31db65d4013bab30e8c815638fbaa32575ce8a2 (patch) | |
| tree | 3cf1b64171fceb8a4645f6379e0dc9955d9c4ff9 /astroid | |
| parent | a59b1cf97a5da7288d8e71791d6b2723df84cc11 (diff) | |
| download | astroid-git-e31db65d4013bab30e8c815638fbaa32575ce8a2.tar.gz | |
Add f-strings with `flynt`
Diffstat (limited to 'astroid')
| -rw-r--r-- | astroid/bases.py | 12 | ||||
| -rw-r--r-- | astroid/brain/brain_builtin_inference.py | 8 | ||||
| -rw-r--r-- | astroid/brain/brain_gi.py | 12 | ||||
| -rw-r--r-- | astroid/brain/brain_namedtuple_enum.py | 18 | ||||
| -rw-r--r-- | astroid/brain/brain_subprocess.py | 22 | ||||
| -rw-r--r-- | astroid/context.py | 3 | ||||
| -rw-r--r-- | astroid/decorators.py | 2 | ||||
| -rw-r--r-- | astroid/exceptions.py | 4 | ||||
| -rw-r--r-- | astroid/interpreter/_import/spec.py | 4 | ||||
| -rw-r--r-- | astroid/nodes/as_string.py | 86 | ||||
| -rw-r--r-- | astroid/nodes/node_classes.py | 8 | ||||
| -rw-r--r-- | astroid/nodes/node_ng.py | 15 |
12 files changed, 77 insertions, 117 deletions
diff --git a/astroid/bases.py b/astroid/bases.py index d32d7353..da4831b4 100644 --- a/astroid/bases.py +++ b/astroid/bases.py @@ -575,12 +575,10 @@ class Generator(BaseInstance): return True def __repr__(self): - return "<Generator({}) l.{} at 0x{}>".format( - self._proxied.name, self.lineno, id(self) - ) + return f"<Generator({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>" def __str__(self): - return "Generator(%s)" % self._proxied.name + return f"Generator({self._proxied.name})" class AsyncGenerator(Generator): @@ -593,9 +591,7 @@ class AsyncGenerator(Generator): return "AsyncGenerator" def __repr__(self): - return "<AsyncGenerator({}) l.{} at 0x{}>".format( - self._proxied.name, self.lineno, id(self) - ) + return f"<AsyncGenerator({self._proxied.name}) l.{self.lineno} at 0x{id(self)}>" def __str__(self): - return "AsyncGenerator(%s)" % self._proxied.name + return f"AsyncGenerator({self._proxied.name})" diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py index 0b3828dd..dc78e836 100644 --- a/astroid/brain/brain_builtin_inference.py +++ b/astroid/brain/brain_builtin_inference.py @@ -668,9 +668,7 @@ def infer_issubclass(callnode, context=None): raise UseInferenceDefault("TypeError: issubclass() takes no keyword arguments") if len(call.positional_arguments) != 2: raise UseInferenceDefault( - "Expected two arguments, got {count}".format( - count=len(call.positional_arguments) - ) + f"Expected two arguments, got {len(call.positional_arguments)}" ) # The left hand argument is the obj to be checked obj_node, class_or_tuple_node = call.positional_arguments @@ -715,9 +713,7 @@ def infer_isinstance(callnode, context=None): raise UseInferenceDefault("TypeError: isinstance() takes no keyword arguments") if len(call.positional_arguments) != 2: raise UseInferenceDefault( - "Expected two arguments, got {count}".format( - count=len(call.positional_arguments) - ) + f"Expected two arguments, got {len(call.positional_arguments)}" ) # The left hand argument is the obj to be checked obj_node, class_or_tuple_node = call.positional_arguments diff --git a/astroid/brain/brain_gi.py b/astroid/brain/brain_gi.py index 89b712c2..2360770a 100644 --- a/astroid/brain/brain_gi.py +++ b/astroid/brain/brain_gi.py @@ -115,7 +115,7 @@ def _gi_build_stub(parent): ret = "" if constants: - ret += "# %s constants\n\n" % parent.__name__ + ret += f"# {parent.__name__} constants\n\n" for name in sorted(constants): if name[0].isdigit(): # GDK has some busted constant names like @@ -132,23 +132,23 @@ def _gi_build_stub(parent): if ret: ret += "\n\n" if functions: - ret += "# %s functions\n\n" % parent.__name__ + ret += f"# {parent.__name__} functions\n\n" for name in sorted(functions): - ret += "def %s(*args, **kwargs):\n" % name + ret += f"def {name}(*args, **kwargs):\n" ret += " pass\n" if ret: ret += "\n\n" if methods: - ret += "# %s methods\n\n" % parent.__name__ + ret += f"# {parent.__name__} methods\n\n" for name in sorted(methods): - ret += "def %s(self, *args, **kwargs):\n" % name + ret += f"def {name}(self, *args, **kwargs):\n" ret += " pass\n" if ret: ret += "\n\n" if classes: - ret += "# %s classes\n\n" % parent.__name__ + ret += f"# {parent.__name__} classes\n\n" for name, obj in sorted(classes.items()): base = "object" if issubclass(obj, Exception): diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py index 83ff5701..1e545f71 100644 --- a/astroid/brain/brain_namedtuple_enum.py +++ b/astroid/brain/brain_namedtuple_enum.py @@ -216,27 +216,21 @@ def infer_named_tuple(node, context=None): for index, name in enumerate(attributes) ) fake = AstroidBuilder(AstroidManager()).string_build( - """ -class %(name)s(tuple): + f""" +class {name}(tuple): __slots__ = () - _fields = %(fields)r + _fields = {attributes!r} def _asdict(self): return self.__dict__ @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): return new(cls, iterable) - def _replace(self, %(replace_args)s): + def _replace(self, {replace_args}): return self def __getnewargs__(self): return tuple(self) -%(field_defs)s +{field_defs} """ - % { - "name": name, - "fields": attributes, - "field_defs": field_defs, - "replace_args": replace_args, - } ) class_node.locals["_asdict"] = fake.body[0].locals["_asdict"] class_node.locals["_make"] = fake.body[0].locals["_make"] @@ -539,7 +533,7 @@ def infer_typing_namedtuple(node, context=None): typename = node.args[0].as_string() if names: - field_names = "({},)".format(",".join(names)) + field_names = f"({','.join(names)},)" else: field_names = "''" node = extract_node(f"namedtuple({typename}, {field_names})") diff --git a/astroid/brain/brain_subprocess.py b/astroid/brain/brain_subprocess.py index 18c128e4..8e239543 100644 --- a/astroid/brain/brain_subprocess.py +++ b/astroid/brain/brain_subprocess.py @@ -93,8 +93,8 @@ def _subprocess_transform(): """.strip() code = textwrap.dedent( - """ - def %(check_output_signature)s + f""" + def {check_output_signature} if universal_newlines: return "" return b"" @@ -102,11 +102,11 @@ def _subprocess_transform(): class Popen(object): returncode = pid = 0 stdin = stdout = stderr = file() - %(py3_args)s + {py3_args} - %(communicate_signature)s: - return %(communicate)r - %(wait_signature)s: + {communicate_signature}: + return {communicate!r} + {wait_signature}: return self.returncode def poll(self): return self.returncode @@ -116,16 +116,8 @@ def _subprocess_transform(): pass def kill(self): pass - %(ctx_manager)s + {ctx_manager} """ - % { - "check_output_signature": check_output_signature, - "communicate": communicate, - "communicate_signature": communicate_signature, - "wait_signature": wait_signature, - "ctx_manager": ctx_manager, - "py3_args": py3_args, - } ) if PY39_PLUS: code += """ diff --git a/astroid/context.py b/astroid/context.py index 39f3f1fc..94248138 100644 --- a/astroid/context.py +++ b/astroid/context.py @@ -155,8 +155,7 @@ class InferenceContext: def __str__(self): state = ( - "%s=%s" - % (field, pprint.pformat(getattr(self, field), width=80 - len(field))) + f"{field}={pprint.pformat(getattr(self, field), width=80 - len(field))}" for field in self.__slots__ ) return "{}({})".format(type(self).__name__, ",\n ".join(state)) diff --git a/astroid/decorators.py b/astroid/decorators.py index 6a32aeb8..5e671e5e 100644 --- a/astroid/decorators.py +++ b/astroid/decorators.py @@ -72,7 +72,7 @@ class cachedproperty: try: wrapped.__name__ except AttributeError as exc: - raise TypeError("%s must have a __name__ attribute" % wrapped) from exc + raise TypeError(f"{wrapped} must have a __name__ attribute") from exc self.wrapped = wrapped @property diff --git a/astroid/exceptions.py b/astroid/exceptions.py index 260657c3..39a6fb12 100644 --- a/astroid/exceptions.py +++ b/astroid/exceptions.py @@ -155,9 +155,7 @@ class MroError(ResolveError): cls = None def __str__(self): - mro_names = ", ".join( - "({})".format(", ".join(b.name for b in m)) for m in self.mros - ) + mro_names = ", ".join(f"({', '.join(b.name for b in m)})" for m in self.mros) return self.message.format(mros=mro_names, cls=self.cls) diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py index 1bf94769..610f45df 100644 --- a/astroid/interpreter/_import/spec.py +++ b/astroid/interpreter/_import/spec.py @@ -319,7 +319,7 @@ def _search_zip(modpath, pic): os.path.abspath(filepath) + os.path.sep + os.path.sep.join(modpath), filepath, ) - raise ImportError("No module named %s" % ".".join(modpath)) + raise ImportError(f"No module named {'.'.join(modpath)}") def _find_spec_with_path(search_path, modname, module_parts, processed, submodule_path): @@ -330,7 +330,7 @@ def _find_spec_with_path(search_path, modname, module_parts, processed, submodul continue return finder, spec - raise ImportError("No module named %s" % ".".join(module_parts)) + raise ImportError(f"No module named {'.'.join(module_parts)}") def find_spec(modpath, path=None): diff --git a/astroid/nodes/as_string.py b/astroid/nodes/as_string.py index 252605a3..93be8fc3 100644 --- a/astroid/nodes/as_string.py +++ b/astroid/nodes/as_string.py @@ -69,7 +69,7 @@ class AsStringVisitor: def _precedence_parens(self, node, child, is_left=True): """Wrap child in parens only if required to keep same semantics""" if self._should_wrap(node, child, is_left): - return "(%s)" % child.accept(self) + return f"({child.accept(self)})" return child.accept(self) @@ -98,13 +98,13 @@ class AsStringVisitor: # visit_<node> methods ########################################### def visit_await(self, node): - return "await %s" % node.value.accept(self) + return f"await {node.value.accept(self)}" def visit_asyncwith(self, node): - return "async %s" % self.visit_with(node) + return f"async {self.visit_with(node)}" def visit_asyncfor(self, node): - return "async %s" % self.visit_for(node) + return f"async {self.visit_for(node)}" def visit_arguments(self, node): """return an astroid.Function node as string""" @@ -117,10 +117,8 @@ class AsStringVisitor: def visit_assert(self, node): """return an astroid.Assert node as string""" if node.fail: - return "assert {}, {}".format( - node.test.accept(self), node.fail.accept(self) - ) - return "assert %s" % node.test.accept(self) + return f"assert {node.test.accept(self)}, {node.fail.accept(self)}" + return f"assert {node.test.accept(self)}" def visit_assignname(self, node): """return an astroid.AssName node as string""" @@ -133,9 +131,7 @@ class AsStringVisitor: def visit_augassign(self, node): """return an astroid.AugAssign node as string""" - return "{} {} {}".format( - node.target.accept(self), node.op, node.value.accept(self) - ) + return f"{node.target.accept(self)} {node.op} {node.value.accept(self)}" def visit_annassign(self, node): """Return an astroid.AugAssign node as string""" @@ -157,8 +153,8 @@ class AsStringVisitor: def visit_boolop(self, node): """return an astroid.BoolOp node as string""" - values = ["%s" % self._precedence_parens(node, n) for n in node.values] - return (" %s " % node.op).join(values) + values = [f"{self._precedence_parens(node, n)}" for n in node.values] + return (f" {node.op} ").join(values) def visit_break(self, node): """return an astroid.Break node as string""" @@ -174,7 +170,7 @@ class AsStringVisitor: keywords = [] args.extend(keywords) - return "{}({})".format(expr_str, ", ".join(args)) + return f"{expr_str}({', '.join(args)})" def visit_classdef(self, node): """return an astroid.ClassDef node as string""" @@ -183,7 +179,7 @@ class AsStringVisitor: if node._metaclass and not node.has_metaclass_hack(): args.append("metaclass=" + node._metaclass.accept(self)) args += [n.accept(self) for n in node.keywords] - args = "(%s)" % ", ".join(args) if args else "" + args = f"({', '.join(args)})" if args else "" docs = self._docs_dedent(node.doc) if node.doc else "" return "\n\n{}class {}{}:{}\n{}\n".format( decorate, node.name, args, docs, self._stmt_list(node.body) @@ -199,11 +195,9 @@ class AsStringVisitor: def visit_comprehension(self, node): """return an astroid.Comprehension node as string""" - ifs = "".join(" if %s" % n.accept(self) for n in node.ifs) - generated = "for {} in {}{}".format( - node.target.accept(self), node.iter.accept(self), ifs - ) - return "{}{}".format("async " if node.is_async else "", generated) + ifs = "".join(f" if {n.accept(self)}" for n in node.ifs) + generated = f"for {node.target.accept(self)} in {node.iter.accept(self)}{ifs}" + return f"{'async ' if node.is_async else ''}{generated}" def visit_const(self, node): """return an astroid.Const node as string""" @@ -217,7 +211,7 @@ class AsStringVisitor: def visit_delete(self, node): # XXX check if correct """return an astroid.Delete node as string""" - return "del %s" % ", ".join(child.accept(self) for child in node.targets) + return f"del {', '.join(child.accept(self) for child in node.targets)}" def visit_delattr(self, node): """return an astroid.DelAttr node as string""" @@ -267,11 +261,9 @@ class AsStringVisitor: def visit_excepthandler(self, node): if node.type: if node.name: - excs = "except {} as {}".format( - node.type.accept(self), node.name.accept(self) - ) + excs = f"except {node.type.accept(self)} as {node.name.accept(self)}" else: - excs = "except %s" % node.type.accept(self) + excs = f"except {node.type.accept(self)}" else: excs = "except" return f"{excs}:\n{self._stmt_list(node.body)}" @@ -367,20 +359,20 @@ class AsStringVisitor: """return an astroid.Getattr node as string""" left = self._precedence_parens(node, node.expr) if left.isdigit(): - left = "(%s)" % left + left = f"({left})" return f"{left}.{node.attrname}" def visit_global(self, node): """return an astroid.Global node as string""" - return "global %s" % ", ".join(node.names) + return f"global {', '.join(node.names)}" def visit_if(self, node): """return an astroid.If node as string""" ifs = [f"if {node.test.accept(self)}:\n{self._stmt_list(node.body)}"] if node.has_elif_block(): - ifs.append("el%s" % self._stmt_list(node.orelse, indent=False)) + ifs.append(f"el{self._stmt_list(node.orelse, indent=False)}") elif node.orelse: - ifs.append("else:\n%s" % self._stmt_list(node.orelse)) + ifs.append(f"else:\n{self._stmt_list(node.orelse)}") return "\n".join(ifs) def visit_ifexp(self, node): @@ -393,12 +385,12 @@ class AsStringVisitor: def visit_import(self, node): """return an astroid.Import node as string""" - return "import %s" % _import_string(node.names) + return f"import {_import_string(node.names)}" def visit_keyword(self, node): """return an astroid.Keyword node as string""" if node.arg is None: - return "**%s" % node.value.accept(self) + return f"**{node.value.accept(self)}" return f"{node.arg}={node.value.accept(self)}" def visit_lambda(self, node): @@ -408,11 +400,11 @@ class AsStringVisitor: if args: return f"lambda {args}: {body}" - return "lambda: %s" % body + return f"lambda: {body}" def visit_list(self, node): """return an astroid.List node as string""" - return "[%s]" % ", ".join(child.accept(self) for child in node.elts) + return f"[{', '.join(child.accept(self) for child in node.elts)}]" def visit_listcomp(self, node): """return an astroid.ListComp node as string""" @@ -422,7 +414,7 @@ class AsStringVisitor: def visit_module(self, node): """return an astroid.Module node as string""" - docs = '"""%s"""\n\n' % node.doc if node.doc else "" + docs = f'"""{node.doc}"""\n\n' if node.doc else "" return docs + "\n".join(n.accept(self) for n in node.body) + "\n\n" def visit_name(self, node): @@ -437,7 +429,7 @@ class AsStringVisitor: def visit_nonlocal(self, node): """return an astroid.Nonlocal node as string""" - return "nonlocal %s" % ", ".join(node.names) + return f"nonlocal {', '.join(node.names)}" def visit_pass(self, node): """return an astroid.Pass node as string""" @@ -447,20 +439,18 @@ class AsStringVisitor: """return an astroid.Raise node as string""" if node.exc: if node.cause: - return "raise {} from {}".format( - node.exc.accept(self), node.cause.accept(self) - ) - return "raise %s" % node.exc.accept(self) + return f"raise {node.exc.accept(self)} from {node.cause.accept(self)}" + return f"raise {node.exc.accept(self)}" return "raise" def visit_return(self, node): """return an astroid.Return node as string""" if node.is_tuple_return() and len(node.value.elts) > 1: elts = [child.accept(self) for child in node.value.elts] - return "return %s" % ", ".join(elts) + return f"return {', '.join(elts)}" if node.value: - return "return %s" % node.value.accept(self) + return f"return {node.value.accept(self)}" return "return" @@ -497,11 +487,11 @@ class AsStringVisitor: def visit_tryexcept(self, node): """return an astroid.TryExcept node as string""" - trys = ["try:\n%s" % self._stmt_list(node.body)] + trys = [f"try:\n{self._stmt_list(node.body)}"] for handler in node.handlers: trys.append(handler.accept(self)) if node.orelse: - trys.append("else:\n%s" % self._stmt_list(node.orelse)) + trys.append(f"else:\n{self._stmt_list(node.orelse)}") return "\n".join(trys) def visit_tryfinally(self, node): @@ -513,8 +503,8 @@ class AsStringVisitor: def visit_tuple(self, node): """return an astroid.Tuple node as string""" if len(node.elts) == 1: - return "(%s, )" % node.elts[0].accept(self) - return "(%s)" % ", ".join(child.accept(self) for child in node.elts) + return f"({node.elts[0].accept(self)}, )" + return f"({', '.join(child.accept(self) for child in node.elts)})" def visit_unaryop(self, node): """return an astroid.UnaryOp node as string""" @@ -526,9 +516,7 @@ class AsStringVisitor: def visit_while(self, node): """return an astroid.While node as string""" - whiles = "while {}:\n{}".format( - node.test.accept(self), self._stmt_list(node.body) - ) + whiles = f"while {node.test.accept(self)}:\n{self._stmt_list(node.body)}" if node.orelse: whiles = f"{whiles}\nelse:\n{self._stmt_list(node.orelse)}" return whiles @@ -536,7 +524,7 @@ class AsStringVisitor: def visit_with(self, node): # 'with' without 'as' is possible """return an astroid.With node as string""" items = ", ".join( - ("%s" % expr.accept(self)) + (v and " as %s" % (v.accept(self)) or "") + f"{expr.accept(self)}" + (v and f" as {v.accept(self)}" or "") for expr, v in node.items ) return f"with {items}:\n{self._stmt_list(node.body)}" diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py index c506d23b..c54f82e2 100644 --- a/astroid/nodes/node_classes.py +++ b/astroid/nodes/node_classes.py @@ -236,7 +236,7 @@ def _container_getitem(instance, elts, index, context=None): message="Type error {error!r}", node=instance, index=index, context=context ) from exc - raise AstroidTypeError("Could not use %s as subscript index" % index) + raise AstroidTypeError(f"Could not use {index} as subscript index") class Statement(NodeNG): @@ -947,7 +947,7 @@ class Arguments(mixins.AssignTypeMixin, NodeNG): ) ) if self.vararg: - result.append("*%s" % self.vararg) + result.append(f"*{self.vararg}") if self.kwonlyargs: if not self.vararg: result.append("*") @@ -957,7 +957,7 @@ class Arguments(mixins.AssignTypeMixin, NodeNG): ) ) if self.kwarg: - result.append("**%s" % self.kwarg) + result.append(f"**{self.kwarg}") return ", ".join(result) def default_value(self, argname): @@ -1071,7 +1071,7 @@ def _format_args(args, defaults=None, annotations=None): packed = itertools.zip_longest(args, annotations) for i, (arg, annotation) in enumerate(packed): if isinstance(arg, Tuple): - values.append("(%s)" % _format_args(arg.elts)) + values.append(f"({_format_args(arg.elts)})") else: argname = arg.name default_sep = "=" diff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py index 5aed3ec4..147e6922 100644 --- a/astroid/nodes/node_ng.py +++ b/astroid/nodes/node_ng.py @@ -177,7 +177,7 @@ class NodeNG: inner = [lines[0]] for line in lines[1:]: inner.append(" " * alignment + line) - result.append("{}={}".format(field, "".join(inner))) + result.append(f"{field}={''.join(inner)}") return string % { "cname": cname, @@ -651,10 +651,7 @@ class NodeNG: """Outputs a strings representation of an astroid node.""" if node in done: result.append( - indent - + "<Recursion on {} with id={}".format( - type(node).__name__, id(node) - ) + indent + f"<Recursion on {type(node).__name__} with id={id(node)}" ) return False done.add(node) @@ -667,7 +664,7 @@ class NodeNG: if ids: result.append(f"{type(node).__name__}<0x{id(node):x}>(\n") else: - result.append("%s(" % type(node).__name__) + result.append(f"{type(node).__name__}(") fields = [] if include_linenos: fields.extend(("lineno", "col_offset")) @@ -678,7 +675,7 @@ class NodeNG: if not fields: broken = False elif len(fields) == 1: - result.append("%s=" % fields[0]) + result.append(f"{fields[0]}=") broken = _repr_tree( getattr(node, fields[0]), result, done, cur_indent, depth ) @@ -686,11 +683,11 @@ class NodeNG: result.append("\n") result.append(cur_indent) for field in fields[:-1]: - result.append("%s=" % field) + result.append(f"{field}=") _repr_tree(getattr(node, field), result, done, cur_indent, depth) result.append(",\n") result.append(cur_indent) - result.append("%s=" % fields[-1]) + result.append(f"{fields[-1]}=") _repr_tree(getattr(node, fields[-1]), result, done, cur_indent, depth) broken = True result.append(")") |
