From 02afad102bef067779fbc846001654dda8f54c7e Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 17 Aug 2023 22:58:07 +0300 Subject: [PATCH] Upgrade syntax with pyupgrade --py38-plus --- examples/func_calls.py | 2 +- examples/func_defs.py | 2 +- pycparser/_ast_gen.py | 4 ++-- pycparser/c_generator.py | 6 +++--- pycparser/ply/lex.py | 12 ++++++------ pycparser/ply/yacc.py | 16 ++++++++-------- pycparser/plyparser.py | 6 +++--- 7 files changed, 24 insertions(+), 24 deletions(-) diff --git a/examples/func_calls.py b/examples/func_calls.py index 8162999f..772a8249 100644 --- a/examples/func_calls.py +++ b/examples/func_calls.py @@ -22,7 +22,7 @@ def __init__(self, funcname): def visit_FuncCall(self, node): if node.name.name == self.funcname: - print('{} called at {}'.format(self.funcname, node.name.coord)) + print(f'{self.funcname} called at {node.name.coord}') # Visit args in case they contain more func calls. if node.args: self.visit(node.args) diff --git a/examples/func_defs.py b/examples/func_defs.py index feecda0b..d3f79ca5 100644 --- a/examples/func_defs.py +++ b/examples/func_defs.py @@ -23,7 +23,7 @@ # locations of function definitions. class FuncDefVisitor(c_ast.NodeVisitor): def visit_FuncDef(self, node): - print('{} at {}'.format(node.decl.name, node.decl.coord)) + print(f'{node.decl.name} at {node.decl.coord}') def show_func_defs(filename): diff --git a/pycparser/_ast_gen.py b/pycparser/_ast_gen.py index 8d37cd75..752557e3 100644 --- a/pycparser/_ast_gen.py +++ b/pycparser/_ast_gen.py @@ -47,7 +47,7 @@ def parse_cfgfile(self, filename): lbracket_i = line.find('[') rbracket_i = line.find(']') if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i: - raise RuntimeError("Invalid line in {}:\n{}\n".format(filename, line)) + raise RuntimeError(f"Invalid line in {filename}:\n{line}\n") name = line[:colon_i] val = line[lbracket_i + 1:rbracket_i] @@ -104,7 +104,7 @@ def _gen_init(self): src += " def __init__%s:\n" % arglist for name in self.all_entries + ['coord']: - src += " self.{} = {}\n".format(name, name) + src += f" self.{name} = {name}\n" return src diff --git a/pycparser/c_generator.py b/pycparser/c_generator.py index 20537484..8791c6b4 100644 --- a/pycparser/c_generator.py +++ b/pycparser/c_generator.py @@ -74,7 +74,7 @@ def visit_UnaryOp(self, n): elif n.op == 'p--': return '%s--' % operand else: - return '{}{}'.format(n.op, operand) + return f'{n.op}{operand}' # Precedence map of binary operators: precedence_map = { @@ -119,13 +119,13 @@ def visit_BinaryOp(self, n): lambda d: not (self._is_simple_node(d) or self.reduce_parentheses and isinstance(d, c_ast.BinaryOp) and self.precedence_map[d.op] > self.precedence_map[n.op])) - return '{} {} {}'.format(lval_str, n.op, rval_str) + return f'{lval_str} {n.op} {rval_str}' def visit_Assignment(self, n): rval_str = self._parenthesize_if( n.rvalue, lambda n: isinstance(n, c_ast.Assignment)) - return '{} {} {}'.format(self.visit(n.lvalue), n.op, rval_str) + return f'{self.visit(n.lvalue)} {n.op} {rval_str}' def visit_IdentifierType(self, n): return ' '.join(n.names) diff --git a/pycparser/ply/lex.py b/pycparser/ply/lex.py index ca1b92b4..cea7eebf 100644 --- a/pycparser/ply/lex.py +++ b/pycparser/ply/lex.py @@ -177,7 +177,7 @@ def writetab(self, lextab, outputdir=''): basetabmodule = lextab.split('.')[-1] filename = os.path.join(outputdir, basetabmodule) + '.py' with open(filename, 'w') as tf: - tf.write('# {}.py. This file automatically created by PLY (version {}). Don\'t edit!\n'.format(basetabmodule, __version__)) + tf.write(f'# {basetabmodule}.py. This file automatically created by PLY (version {__version__}). Don\'t edit!\n') tf.write('_tabversion = %s\n' % repr(__tabversion__)) tf.write('_lextokens = set(%s)\n' % repr(tuple(self.lextokens))) tf.write('_lexreflags = %s\n' % repr(self.lexreflags)) @@ -758,7 +758,7 @@ def validate_rules(self): continue try: - c = re.compile('(?P<{}>{})'.format(fname, _get_regex(f)), self.reflags) + c = re.compile(f'(?P<{fname}>{_get_regex(f)})', self.reflags) if c.match(''): self.log.error("%s:%d: Regular expression for rule '%s' matches empty string", file, line, f.__name__) self.error = True @@ -782,7 +782,7 @@ def validate_rules(self): continue try: - c = re.compile('(?P<{}>{})'.format(name, r), self.reflags) + c = re.compile(f'(?P<{name}>{r})', self.reflags) if (c.match('')): self.log.error("Regular expression for rule '%s' matches empty string", name) self.error = True @@ -951,13 +951,13 @@ def lex(module=None, object=None, debug=False, optimize=False, lextab='lextab', for fname, f in linfo.funcsym[state]: line = f.__code__.co_firstlineno file = f.__code__.co_filename - regex_list.append('(?P<{}>{})'.format(fname, _get_regex(f))) + regex_list.append(f'(?P<{fname}>{_get_regex(f)})') if debug: debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", fname, _get_regex(f), state) # Now add all of the simple rules for name, r in linfo.strsym[state]: - regex_list.append('(?P<{}>{})'.format(name, r)) + regex_list.append(f'(?P<{name}>{r})') if debug: debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", name, r, state) @@ -1042,7 +1042,7 @@ def lex(module=None, object=None, debug=False, optimize=False, lextab='lextab', try: lexobj.writetab(lextab, outputdir) except OSError as e: - errorlog.warning("Couldn't write lextab module {!r}. {}".format(lextab, e)) + errorlog.warning(f"Couldn't write lextab module {lextab!r}. {e}") return lexobj diff --git a/pycparser/ply/yacc.py b/pycparser/ply/yacc.py index e5ac723b..a6977041 100644 --- a/pycparser/ply/yacc.py +++ b/pycparser/ply/yacc.py @@ -142,7 +142,7 @@ def format_result(r): repr_str = repr(repr_str) if len(repr_str) > resultlimit: repr_str = repr_str[:resultlimit] + ' ...' - result = '<{} @ 0x{:x}> ({})'.format(type(r).__name__, id(r), repr_str) + result = f'<{type(r).__name__} @ 0x{id(r):x}> ({repr_str})' return result # Format stack entries when the parser is running in debug mode @@ -153,7 +153,7 @@ def format_stack_entry(r): if len(repr_str) < 16: return repr_str else: - return '<{} @ 0x{:x}>'.format(type(r).__name__, id(r)) + return f'<{type(r).__name__} @ 0x{id(r):x}>' # Panic mode error recovery support. This feature is being reworked--much of the # code here is to offer a deprecation/backwards compatible transition @@ -1592,7 +1592,7 @@ def add_production(self, prodname, syms, func=None, file='', line=0): prodprec = self.Precedence.get(precname, ('right', 0)) # See if the rule is already in the rulemap - map = '{} -> {}'.format(prodname, syms) + map = f'{prodname} -> {syms}' if map in self.Prodmap: m = self.Prodmap[map] raise GrammarError('%s:%d: Duplicate rule %s. ' % (file, line, m) + @@ -2782,7 +2782,7 @@ def write_table(self, tabmodule, outputdir='', signature=''): else: f.write('\n_lr_action = { ') for k, v in self.lr_action.items(): - f.write('({!r},{!r}):{!r},'.format(k[0], k[1], v)) + f.write(f'({k[0]!r},{k[1]!r}):{v!r},') f.write('}\n') if smaller: @@ -2821,7 +2821,7 @@ def write_table(self, tabmodule, outputdir='', signature=''): else: f.write('\n_lr_goto = { ') for k, v in self.lr_goto.items(): - f.write('({!r},{!r}):{!r},'.format(k[0], k[1], v)) + f.write(f'({k[0]!r},{k[1]!r}):{v!r},') f.write('}\n') # Write production table @@ -3303,7 +3303,7 @@ def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, star try: debuglog = PlyLogger(open(os.path.join(outputdir, debugfile), 'w')) except OSError as e: - errorlog.warning("Couldn't open {!r}. {}".format(debugfile, e)) + errorlog.warning(f"Couldn't open {debugfile!r}. {e}") debuglog = NullLogger() else: debuglog = NullLogger() @@ -3477,14 +3477,14 @@ def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, star try: lr.write_table(tabmodule, outputdir, signature) except OSError as e: - errorlog.warning("Couldn't create {!r}. {}".format(tabmodule, e)) + errorlog.warning(f"Couldn't create {tabmodule!r}. {e}") # Write a pickled version of the tables if picklefile: try: lr.pickle_table(picklefile, signature) except OSError as e: - errorlog.warning("Couldn't create {!r}. {}".format(picklefile, e)) + errorlog.warning(f"Couldn't create {picklefile!r}. {e}") # Build the parser lr.bind_callables(pinfo.pdict) diff --git a/pycparser/plyparser.py b/pycparser/plyparser.py index fcb64b24..994a8cd4 100644 --- a/pycparser/plyparser.py +++ b/pycparser/plyparser.py @@ -23,7 +23,7 @@ def __init__(self, file, line, column=None): self.column = column def __str__(self): - str = "{}:{}".format(self.file, self.line) + str = f"{self.file}:{self.line}" if self.column: str += ":%s" % self.column return str @@ -42,7 +42,7 @@ def _create_opt_rule(self, rulename): def optrule(self, p): p[0] = p[1] - optrule.__doc__ = '{} : empty\n| {}'.format(optname, rulename) + optrule.__doc__ = f'{optname} : empty\n| {rulename}' optrule.__name__ = 'p_%s' % optname setattr(self.__class__, optrule.__name__, optrule) @@ -64,7 +64,7 @@ def _token_coord(self, p, token_idx): return self._coord(p.lineno(token_idx), column) def _parse_error(self, msg, coord): - raise ParseError("{}: {}".format(coord, msg)) + raise ParseError(f"{coord}: {msg}") def parameterized(*params):