Skip to content

Commit

Permalink
Upgrade syntax with pyupgrade --py38-plus
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Aug 17, 2023
1 parent c370d67 commit 02afad1
Show file tree
Hide file tree
Showing 7 changed files with 24 additions and 24 deletions.
2 changes: 1 addition & 1 deletion examples/func_calls.py
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion examples/func_defs.py
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions pycparser/_ast_gen.py
Expand Up @@ -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]
Expand Down Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions pycparser/c_generator.py
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 6 additions & 6 deletions pycparser/ply/lex.py
Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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

Expand Down
16 changes: 8 additions & 8 deletions pycparser/ply/yacc.py
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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) +
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions pycparser/plyparser.py
Expand Up @@ -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

Expand All @@ -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)

Expand All @@ -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):
Expand Down

0 comments on commit 02afad1

Please sign in to comment.