Skip to content

Commit

Permalink
Merge pull request #2661 from danieleades/pyupgrade
Browse files Browse the repository at this point in the history
add pyupgrade lint group
  • Loading branch information
Anteru committed Mar 29, 2024
2 parents c140bfd + cebba07 commit eeb568d
Show file tree
Hide file tree
Showing 55 changed files with 371 additions and 464 deletions.
4 changes: 2 additions & 2 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@
# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}

rst_prolog = '.. |language_count| replace:: {}'.format(len(list(pygments.lexers.get_all_lexers())))
rst_prolog = f'.. |language_count| replace:: {len(list(pygments.lexers.get_all_lexers()))}'

def pg_context(app, pagename, templatename, ctx, event_arg):
ctx['demo_active'] = bool(os.environ.get('WEBSITE_BUILD'))
Expand Down Expand Up @@ -284,7 +284,7 @@ def source_read(app, docname, source):

def linkify(match):
url = 'https://github.com/pygments/pygments/issues/' + match[1]
return '`{} <{}>`_'.format(match[0], url)
return f'`{match[0]} <{url}>`_'

linkified = re.sub(r'(?:PR)?#([0-9]+)\b', linkify, changelog[:idx])
source[0] = linkified + changelog[idx:]
Expand Down
2 changes: 1 addition & 1 deletion doc/examples/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ def fib(n: int) -> Iterator[int]:
a, b = b, a + b

result = sum(Math.fib(42))
print("The answer is {}".format(result))
print(f"The answer is {result}")
4 changes: 2 additions & 2 deletions pygments/cmdline.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def _print_list(what):
info.append(tup)
info.sort()
for i in info:
print(('* %s\n %s %s') % i)
print(('* {}\n {} {}').format(*i))

elif what == 'formatter':
print()
Expand All @@ -112,7 +112,7 @@ def _print_list(what):
info.append(tup)
info.sort()
for i in info:
print(('* %s\n %s %s') % i)
print(('* {}\n {} {}').format(*i))

elif what == 'filter':
print()
Expand Down
5 changes: 2 additions & 3 deletions pygments/formatters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,12 @@ def load_formatter_from_file(filename, formattername="CustomFormatter", **option
exec(f.read(), custom_namespace)
# Retrieve the class `formattername` from that namespace
if formattername not in custom_namespace:
raise ClassNotFound('no valid %s class found in %s' %
(formattername, filename))
raise ClassNotFound(f'no valid {formattername} class found in {filename}')
formatter_class = custom_namespace[formattername]
# And finally instantiate it with the options
return formatter_class(**options)
except OSError as err:
raise ClassNotFound('cannot read %s: %s' % (filename, err))
raise ClassNotFound(f'cannot read {filename}: {err}')
except ClassNotFound:
raise
except Exception as err:
Expand Down
35 changes: 16 additions & 19 deletions pygments/formatters/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ def get_token_style_defs(self, arg=None):
styles.sort()

lines = [
'%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:])
f'{prefix(cls)} {{ {style} }} /* {repr(ttype)[6:]} */'
for (level, ttype, cls, style) in styles
]

Expand All @@ -548,13 +548,13 @@ def get_background_style_defs(self, arg=None):
if Text in self.ttype2class:
text_style = ' ' + self.class2style[self.ttype2class[Text]][0]
lines.insert(
0, '%s{ background: %s;%s }' % (
0, '{}{{ background: {};{} }}'.format(
prefix(''), bg_color, text_style
)
)
if hl_color is not None:
lines.insert(
0, '%s { background-color: %s }' % (prefix('hll'), hl_color)
0, '{} {{ background-color: {} }}'.format(prefix('hll'), hl_color)
)

return lines
Expand Down Expand Up @@ -594,17 +594,15 @@ def _pre_style(self):

@property
def _linenos_style(self):
return 'color: %s; background-color: %s; padding-left: 5px; padding-right: 5px;' % (
self.style.line_number_color,
self.style.line_number_background_color
)
color = self.style.line_number_color
background_color = self.style.line_number_background_color
return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'

@property
def _linenos_special_style(self):
return 'color: %s; background-color: %s; padding-left: 5px; padding-right: 5px;' % (
self.style.line_number_special_color,
self.style.line_number_special_background_color
)
color = self.style.line_number_special_color
background_color = self.style.line_number_special_background_color
return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'

def _decodeifneeded(self, value):
if isinstance(value, bytes):
Expand Down Expand Up @@ -695,7 +693,7 @@ def _wrap_tablelinenos(self, inner):
style = ' class="normal"'

if style:
line = '<span%s>%s</span>' % (style, line)
line = f'<span{style}>{line}</span>'

lines.append(line)

Expand Down Expand Up @@ -754,7 +752,7 @@ def _wrap_inlinelinenos(self, inner):
style = ' class="linenos"'

if style:
linenos = '<span%s>%s</span>' % (style, line)
linenos = f'<span{style}>{line}</span>'
else:
linenos = line

Expand Down Expand Up @@ -791,7 +789,7 @@ def _wrap_div(self, inner):
style = []
if (self.noclasses and not self.nobackground and
self.style.background_color is not None):
style.append('background: %s' % (self.style.background_color,))
style.append(f'background: {self.style.background_color}')
if self.cssstyles:
style.append(self.cssstyles)
style = '; '.join(style)
Expand Down Expand Up @@ -848,13 +846,13 @@ def _format_lines(self, tokensource):
css_style = self._get_css_inline_styles(ttype)
if css_style:
css_style = self.class2style[css_style][0]
cspan = '<span style="%s"%s>' % (css_style, title)
cspan = f'<span style="{css_style}"{title}>'
else:
cspan = ''
else:
css_class = self._get_css_classes(ttype)
if css_class:
cspan = '<span class="%s"%s>' % (css_class, title)
cspan = f'<span class="{css_class}"{title}>'
else:
cspan = ''
self.span_element_openers[ttype] = cspan
Expand Down Expand Up @@ -927,9 +925,8 @@ def _highlight_lines(self, tokensource):
if self.noclasses:
style = ''
if self.style.highlight_color is not None:
style = (' style="background-color: %s"' %
(self.style.highlight_color,))
yield 1, '<span%s>%s</span>' % (style, value)
style = (f' style="background-color: {self.style.highlight_color}"')
yield 1, f'<span{style}>{value}</span>'
else:
yield 1, '<span class="hll">%s</span>' % value
else:
Expand Down
7 changes: 3 additions & 4 deletions pygments/formatters/img.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def __init__(self, font_name, font_size=14):
self._create_nix()

def _get_nix_font_path(self, name, style):
proc = subprocess.Popen(['fc-list', "%s:style=%s" % (name, style), 'file'],
proc = subprocess.Popen(['fc-list', f"{name}:style={style}", 'file'],
stdout=subprocess.PIPE, stderr=None)
stdout, _ = proc.communicate()
if proc.returncode == 0:
Expand Down Expand Up @@ -160,15 +160,14 @@ def _lookup_win(self, key, basename, styles, fail=False):
for suffix in ('', ' (TrueType)'):
for style in styles:
try:
valname = '%s%s%s' % (basename, style and ' '+style, suffix)
valname = '{}{}{}'.format(basename, style and ' '+style, suffix)
val, _ = _winreg.QueryValueEx(key, valname)
return val
except OSError:
continue
else:
if fail:
raise FontNotFound('Font %s (%s) not found in registry' %
(basename, styles[0]))
raise FontNotFound(f'Font {basename} ({styles[0]}) not found in registry')
return None

def _create_win(self):
Expand Down
11 changes: 5 additions & 6 deletions pygments/formatters/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,9 +307,8 @@ def rgbcolor(col):
cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' %
rgbcolor(ndef['color']))
if ndef['border']:
cmndef += (r'\def\$$@bc##1{{\setlength{\fboxsep}{\string -\fboxrule}'
r'\fcolorbox[rgb]{%s}{%s}{\strut ##1}}}' %
(rgbcolor(ndef['border']),
cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{\string -\fboxrule}}'
r'\fcolorbox[rgb]{{{}}}{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['border']),
rgbcolor(ndef['bgcolor'])))
elif ndef['bgcolor']:
cmndef += (r'\def\$$@bc##1{{\setlength{\fboxsep}{0pt}'
Expand All @@ -329,7 +328,7 @@ def get_style_defs(self, arg=''):
cp = self.commandprefix
styles = []
for name, definition in self.cmd2def.items():
styles.append(r'\@namedef{%s@tok@%s}{%s}' % (cp, name, definition))
styles.append(rf'\@namedef{{{cp}@tok@{name}}}{{{definition}}}')
return STYLE_TEMPLATE % {'cp': self.commandprefix,
'styles': '\n'.join(styles)}

Expand Down Expand Up @@ -410,10 +409,10 @@ def format_unencoded(self, tokensource, outfile):
spl = value.split('\n')
for line in spl[:-1]:
if line:
outfile.write("\\%s{%s}{%s}" % (cp, styleval, line))
outfile.write(f"\\{cp}{{{styleval}}}{{{line}}}")
outfile.write('\n')
if spl[-1]:
outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1]))
outfile.write(f"\\{cp}{{{styleval}}}{{{spl[-1]}}}")
else:
outfile.write(value)

Expand Down
2 changes: 1 addition & 1 deletion pygments/formatters/other.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def format(self, tokensource, outfile):
outbuf = []
for ttype, value in tokensource:
rawbuf.append(value)
outbuf.append('%s(%s, %r),\n' % (indentation, ttype, value))
outbuf.append(f'{indentation}({ttype}, {value!r}),\n')

before = TESTCASE_BEFORE % (''.join(rawbuf),)
during = ''.join(outbuf)
Expand Down
13 changes: 5 additions & 8 deletions pygments/formatters/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,7 @@ def format_unencoded(self, tokensource, outfile):
'"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/'
'svg10.dtd">\n')
outfile.write('<svg xmlns="http://www.w3.org/2000/svg">\n')
outfile.write('<g font-family="%s" font-size="%s">\n' %
(self.fontfamily, self.fontsize))
outfile.write(f'<g font-family="{self.fontfamily}" font-size="{self.fontsize}">\n')

counter = self.linenostart
counter_step = self.linenostep
Expand All @@ -141,12 +140,11 @@ def format_unencoded(self, tokensource, outfile):

if self.linenos:
if counter % counter_step == 0:
outfile.write('<text x="%s" y="%s" %s text-anchor="end">%s</text>' %
(x+self.linenowidth,y,counter_style,counter))
outfile.write(f'<text x="{x+self.linenowidth}" y="{y}" {counter_style} text-anchor="end">{counter}</text>')
line_x += self.linenowidth + self.ystep
counter += 1

outfile.write('<text x="%s" y="%s" xml:space="preserve">' % (line_x, y))
outfile.write(f'<text x="{line_x}" y="{y}" xml:space="preserve">')
for ttype, value in tokensource:
style = self._get_style(ttype)
tspan = style and '<tspan' + style + '>' or ''
Expand All @@ -160,11 +158,10 @@ def format_unencoded(self, tokensource, outfile):
y += self.ystep
outfile.write('</text>\n')
if self.linenos and counter % counter_step == 0:
outfile.write('<text x="%s" y="%s" text-anchor="end" %s>%s</text>' %
(x+self.linenowidth,y,counter_style,counter))
outfile.write(f'<text x="{x+self.linenowidth}" y="{y}" text-anchor="end" {counter_style}>{counter}</text>')

counter += 1
outfile.write('<text x="%s" y="%s" ' 'xml:space="preserve">' % (line_x,y))
outfile.write(f'<text x="{line_x}" y="{y}" ' 'xml:space="preserve">')
outfile.write(tspan + parts[-1] + tspanend)
outfile.write('</text>')

Expand Down
11 changes: 4 additions & 7 deletions pygments/lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,7 @@ def __init__(self, **options):

def __repr__(self):
if self.options:
return '<pygments.lexers.%s with %r>' % (self.__class__.__name__,
self.options)
return f'<pygments.lexers.{self.__class__.__name__} with {self.options!r}>'
else:
return '<pygments.lexers.%s>' % self.__class__.__name__

Expand Down Expand Up @@ -511,7 +510,7 @@ def _process_regex(cls, regex, rflags, state):
def _process_token(cls, token):
"""Preprocess the token component of a token definition."""
assert type(token) is _TokenType or callable(token), \
'token type must be simple type or callable, not %r' % (token,)
f'token type must be simple type or callable, not {token!r}'
return token

def _process_new_state(cls, new_state, unprocessed, processed):
Expand Down Expand Up @@ -579,8 +578,7 @@ def _process_state(cls, unprocessed, processed, state):
try:
rex = cls._process_regex(tdef[0], rflags, state)
except Exception as err:
raise ValueError("uncompilable regex %r in state %r of %r: %s" %
(tdef[0], state, cls, err)) from err
raise ValueError(f"uncompilable regex {tdef[0]!r} in state {state!r} of {cls!r}: {err}") from err

token = cls._process_token(tdef[1])

Expand Down Expand Up @@ -773,8 +771,7 @@ def __init__(self, text, pos, stack=None, end=None):
self.stack = stack or ['root']

def __repr__(self):
return 'LexerContext(%r, %r, %r)' % (
self.text, self.pos, self.stack)
return f'LexerContext({self.text!r}, {self.pos!r}, {self.stack!r})'


class ExtendedRegexLexer(RegexLexer):
Expand Down
5 changes: 2 additions & 3 deletions pygments/lexers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,12 @@ def load_lexer_from_file(filename, lexername="CustomLexer", **options):
exec(f.read(), custom_namespace)
# Retrieve the class `lexername` from that namespace
if lexername not in custom_namespace:
raise ClassNotFound('no valid %s class found in %s' %
(lexername, filename))
raise ClassNotFound(f'no valid {lexername} class found in {filename}')
lexer_class = custom_namespace[lexername]
# And finally instantiate it with the options
return lexer_class(**options)
except OSError as err:
raise ClassNotFound('cannot read %s: %s' % (filename, err))
raise ClassNotFound(f'cannot read {filename}: {err}')
except ClassNotFound:
raise
except Exception as err:
Expand Down
2 changes: 1 addition & 1 deletion pygments/lexers/_cocoa_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
with open(headerFilePath, encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
print("Decoding error for file: {0}".format(headerFilePath))
print(f"Decoding error for file: {headerFilePath}")
continue

res = re.findall(r'(?<=@interface )\w+', content)
Expand Down
2 changes: 1 addition & 1 deletion pygments/lexers/_php_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -3299,7 +3299,7 @@ def get_php_references():
download = urlretrieve(PHP_MANUAL_URL)
with tarfile.open(download[0]) as tar:
tar.extractall()
yield from glob.glob("%s%s" % (PHP_MANUAL_DIR, PHP_REFERENCE_GLOB))
yield from glob.glob(f"{PHP_MANUAL_DIR}{PHP_REFERENCE_GLOB}")
os.remove(download[0])

def regenerate(filename, modules):
Expand Down
3 changes: 1 addition & 2 deletions pygments/lexers/_postgres_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,8 +728,7 @@ def update_consts(filename, constname, content):
re_match = re.compile(r'^%s\s*=\s*\($.*?^\s*\)$' % constname, re.M | re.S)
m = re_match.search(data)
if not m:
raise ValueError('Could not find existing definition for %s' %
(constname,))
raise ValueError(f'Could not find existing definition for {constname}')

new_block = format_lines(constname, content)
data = data[:m.start()] + new_block + data[m.end():]
Expand Down
2 changes: 1 addition & 1 deletion pygments/lexers/asm.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,7 +858,7 @@ class TasmLexer(RegexLexer):
include('whitespace'),
(identifier + ':', Name.Label),
(directives, Keyword, 'instruction-args'),
(r'(%s)(\s+)(%s)' % (identifier, datatype),
(rf'({identifier})(\s+)({datatype})',
bygroups(Name.Constant, Whitespace, Keyword.Declaration),
'instruction-args'),
(declkw, Keyword.Declaration, 'instruction-args'),
Expand Down
11 changes: 4 additions & 7 deletions pygments/lexers/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ class BlitzMaxLexer(RegexLexer):
bmax_sktypes = r'@{1,2}|[!#$%]'
bmax_lktypes = r'\b(Int|Byte|Short|Float|Double|Long)\b'
bmax_name = r'[a-z_]\w*'
bmax_var = (r'(%s)(?:(?:([ \t]*)(%s)|([ \t]*:[ \t]*\b(?:Shl|Shr|Sar|Mod)\b)'
r'|([ \t]*)(:)([ \t]*)(?:%s|(%s)))(?:([ \t]*)(Ptr))?)') % \
(bmax_name, bmax_sktypes, bmax_lktypes, bmax_name)
bmax_var = (rf'({bmax_name})(?:(?:([ \t]*)({bmax_sktypes})|([ \t]*:[ \t]*\b(?:Shl|Shr|Sar|Mod)\b)'
rf'|([ \t]*)(:)([ \t]*)(?:{bmax_lktypes}|({bmax_name})))(?:([ \t]*)(Ptr))?)')
bmax_func = bmax_var + r'?((?:[ \t]|\.\.\n)*)([(])'

flags = re.MULTILINE | re.IGNORECASE
Expand Down Expand Up @@ -67,8 +66,7 @@ class BlitzMaxLexer(RegexLexer):
# Identifiers
(r'\b(New)\b([ \t]?)([(]?)(%s)' % (bmax_name),
bygroups(Keyword.Reserved, Whitespace, Punctuation, Name.Class)),
(r'\b(Import|Framework|Module)([ \t]+)(%s\.%s)' %
(bmax_name, bmax_name),
(rf'\b(Import|Framework|Module)([ \t]+)({bmax_name}\.{bmax_name})',
bygroups(Keyword.Reserved, Whitespace, Keyword.Namespace)),
(bmax_func, bygroups(Name.Function, Whitespace, Keyword.Type,
Operator, Whitespace, Punctuation, Whitespace,
Expand Down Expand Up @@ -125,8 +123,7 @@ class BlitzBasicLexer(RegexLexer):

bb_sktypes = r'@{1,2}|[#$%]'
bb_name = r'[a-z]\w*'
bb_var = (r'(%s)(?:([ \t]*)(%s)|([ \t]*)([.])([ \t]*)(?:(%s)))?') % \
(bb_name, bb_sktypes, bb_name)
bb_var = (rf'({bb_name})(?:([ \t]*)({bb_sktypes})|([ \t]*)([.])([ \t]*)(?:({bb_name})))?')

flags = re.MULTILINE | re.IGNORECASE
tokens = {
Expand Down

0 comments on commit eeb568d

Please sign in to comment.