Skip to content

Commit

Permalink
Run pyupgrade --py38-plus
Browse files Browse the repository at this point in the history
  • Loading branch information
facelessuser committed Sep 2, 2023
1 parent 669e5d2 commit c05e0fe
Show file tree
Hide file tree
Showing 14 changed files with 43 additions and 43 deletions.
4 changes: 2 additions & 2 deletions pyspelling/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def _walk_src(self, targets, flags, limit, pipeline, expect_match):
if not found_something and expect_match:
raise RuntimeError(
'None of the source targets from the configuration match any files:\n{}'.format(
'\n'.join('- {}'.format(target) for target in targets)
'\n'.join(f'- {target}' for target in targets)
)
)

Expand Down Expand Up @@ -658,7 +658,7 @@ def spellcheck(config_file, names=None, groups=None, binary='', checker='', sour
else:
raise ValueError('%s is not a valid spellchecker!' % checker)

spellchecker.log('Using %s to spellcheck %s' % (checker, task.get('name', '')), 1)
spellchecker.log('Using {} to spellcheck {}'.format(checker, task.get('name', '')), 1)
for result in spellchecker.run_task(task, source_patterns=sources):
spellchecker.log('Context: %s' % result.context, 2)
yield result
Expand Down
4 changes: 2 additions & 2 deletions pyspelling/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ def run(config, **kwargs):
count += 1
if results.error:
fail = True
print('ERROR: %s -- %s' % (results.context, results.error))
print(f'ERROR: {results.context} -- {results.error}')
elif results.words:
fail = True
print('Misspelled words:\n<%s> %s' % (results.category, results.context))
print(f'Misspelled words:\n<{results.category}> {results.context}')
print('-' * 80)
for word in results.words:
print(word)
Expand Down
14 changes: 7 additions & 7 deletions pyspelling/__meta__.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def __new__(cls, major, minor, micro, release="final", pre=0, post=0, dev=0):
raise ValueError("All version parts except 'release' should be integers.")

if release not in REL_MAP:
raise ValueError("'{}' is not a valid release type.".format(release))
raise ValueError(f"'{release}' is not a valid release type.")

# Ensure valid pre-release (we do not allow implicit pre-releases).
if ".dev-candidate" < release < "final":
Expand Down Expand Up @@ -140,15 +140,15 @@ def _get_canonical(self):

# Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed..
if self.micro == 0:
ver = "{}.{}".format(self.major, self.minor)
ver = f"{self.major}.{self.minor}"
else:
ver = "{}.{}.{}".format(self.major, self.minor, self.micro)
ver = f"{self.major}.{self.minor}.{self.micro}"
if self._is_pre():
ver += '{}{}'.format(REL_MAP[self.release], self.pre)
ver += f'{REL_MAP[self.release]}{self.pre}'
if self._is_post():
ver += ".post{}".format(self.post)
ver += f".post{self.post}"
if self._is_dev():
ver += ".dev{}".format(self.dev)
ver += f".dev{self.dev}"

return ver

Expand All @@ -159,7 +159,7 @@ def parse_version(ver):
m = RE_VER.match(ver)

if m is None:
raise ValueError("'{}' is not a valid version".format(ver))
raise ValueError(f"'{ver}' is not a valid version")

# Handle major, minor, micro
major = int(m.group('major'))
Expand Down
8 changes: 4 additions & 4 deletions pyspelling/filters/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@ def validate_options(self, k, v):
if k == 'delimiters':
for d in v:
if not isinstance(d, (dict, OrderedDict)):
raise ValueError("{}: 'delimters' entries must be of dict type.".format(self.__class__.__name__))
raise ValueError(f"{self.__class__.__name__}: 'delimters' entries must be of dict type.")
for key, value in d.items():
if key not in ('open', 'close', 'content'):
raise KeyError(
"{}: '{}' is not a valid key for a 'delimeters' entry.".format(self.__class__.__name__, key)
f"{self.__class__.__name__}: '{key}' is not a valid key for a 'delimeters' entry."
)
if not isinstance(value, str):
raise ValueError(
"{}: 'delimeters' '{}' key should have str values.".format(self.__class__.__name__, value)
f"{self.__class__.__name__}: 'delimeters' '{value}' key should have str values."
)

def setup(self):
Expand All @@ -63,7 +63,7 @@ def setup(self):
):
group = util.random_name_gen()

pattern = r'%s(?P<%s>%s)(?:%s|\Z)' % (
pattern = r'{}(?P<{}>{})(?:{}|\Z)'.format(
delimiter['open'],
group,
delimiter.get('content', DEFAULT_CONTENT),
Expand Down
6 changes: 3 additions & 3 deletions pyspelling/filters/cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,16 +133,16 @@ def validate_options(self, k, v):
super().validate_options(k, v)
if k == 'charset_size':
if v not in (1, 2, 4):
raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v))
raise ValueError(f"{self.__class__.__name__}: '{v}' is an unsupported charset size")
elif k == 'wide_charset_size':
if v not in (2, 4):
raise ValueError("{}: '{}' is an unsupported wide charset size".format(self.__class__.__name__, v))
raise ValueError(f"{self.__class__.__name__}: '{v}' is an unsupported wide charset size")
elif k in ('exec_charset', 'wide_exec_charset'):
# See if parsing fails.
self.get_encoding_name(v)
elif k == 'string_types':
if RE_VALID_STRING_TYPES.match(v) is None:
raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v))
raise ValueError(f"{self.__class__.__name__}: '{v}' does not define valid string types")

def eval_string_type(self, text, is_string=False):
"""Evaluate string type."""
Expand Down
2 changes: 1 addition & 1 deletion pyspelling/filters/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def validate_options(self, k, v):

super().validate_options(k, v)
if k == 'mode' and v not in MODE:
raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
raise ValueError(f"{self.__class__.__name}: '{v}' is not a valid value for '{k}'")

def setup(self):
"""Setup."""
Expand Down
2 changes: 1 addition & 1 deletion pyspelling/filters/odf.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def extract_tag_metadata(self, el):
if self.type == 'odp':
if el.namespace and el.namespace == self.namespaces['draw'] and el.name == 'page-thumbnail':
name = el.attrs.get('draw:page-number', '')
self.additional_context = 'slide{}:'.format(name)
self.additional_context = f'slide{name}:'
super().extract_tag_metadata(el)

def reset(self):
Expand Down
6 changes: 3 additions & 3 deletions pyspelling/filters/ooxml.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def determine_file_type(self, z):
for o in soup.find_all('Override'):
name = o.attrs.get('PartName')
for k, v in MIMEMAP.items():
if name.startswith('/{}/'.format(k)):
if name.startswith(f'/{k}/'):
self.type = v
break
if self.type:
Expand Down Expand Up @@ -132,9 +132,9 @@ def get_context(self, filename):
"""Get context."""

if self.type == 'pptx':
context = '{}: '.format(RE_SLIDE.search(filename).group(1))
context = f'{RE_SLIDE.search(filename).group(1)}: '
elif self.type == 'docx':
context = '{}: '.format(RE_DOCS.match(filename).group(1))
context = f'{RE_DOCS.match(filename).group(1)}: '
else:
context = ''
return context
Expand Down
16 changes: 8 additions & 8 deletions pyspelling/filters/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def validate_options(self, k, v):
super().validate_options(k, v)
if k == 'string_types':
if RE_VALID_STRING_TYPES.match(v) is None:
raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v))
raise ValueError(f"{self.__class__.__name__}: '{v}' does not define valid string types")

def header_check(self, content):
"""Special Python encoding check."""
Expand Down Expand Up @@ -289,9 +289,9 @@ def _filter(self, text, context, encoding):
if parent != self.MODULE:
prefix = '.' if parent == self.CLASS else ', '
if name == 'class':
stack.append(('%s%s' % (prefix, value), len(indent), self.CLASS))
stack.append((f'{prefix}{value}', len(indent), self.CLASS))
elif name == 'def':
stack.append(('%s%s()' % (prefix, value), len(indent), self.FUNCTION))
stack.append((f'{prefix}{value}()', len(indent), self.FUNCTION))
name = None
elif FSTR_TOKENIZE and token_type == tokenize.FSTRING_START:
dstr = not self.catch_same_level(stack, len(indent)) and (prev_token_type in PREV_DOC_TOKENS)
Expand All @@ -312,9 +312,9 @@ def _filter(self, text, context, encoding):
comments[-1][2] = line_num
else:
if len(stack) > 1:
loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
loc = "{}({}): {}".format(stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
else:
loc = "%s(%s)" % (stack[0][0], line)
loc = f"{stack[0][0]}({line})"
comments.append([value[1:], loc, line_num])

if FSTR_TOKENIZE and token_type == tokenize.FSTRING_MIDDLE and fstring_stack[-1][0]:
Expand All @@ -326,7 +326,7 @@ def _filter(self, text, context, encoding):
docstrings=dstr
)
if string:
loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
loc = "{}({}): {}".format(stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
strings.append(filters.SourceText(string, loc, 'utf-8', 'py-string'))

if token_type == tokenize.STRING:
Expand All @@ -340,15 +340,15 @@ def _filter(self, text, context, encoding):
value = value.strip()
string, _is_bytes = self.process_strings(value, docstrings=True)
if string:
loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
loc = "{}({}): {}".format(stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
docstrings.append(
filters.SourceText(string, loc, 'utf-8', 'py-docstring')
)
elif self.strings:
value = value.strip()
string, _is_bytes = self.process_strings(value)
if string:
loc = "%s(%s): %s" % (stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
loc = "{}({}): {}".format(stack[0][0], line, ''.join([crumb[0] for crumb in stack[1:]]))
strings.append(filters.SourceText(string, loc, 'utf-8', 'py-string'))

if token_type == tokenize.INDENT:
Expand Down
2 changes: 1 addition & 1 deletion pyspelling/filters/stylesheets.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def validate_options(self, k, v):

super().validate_options(k, v)
if k == 'stylesheets' and v not in STYLESHEET_TYPE:
raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
raise ValueError(f"{self.__class__.__name}: '{v}' is not a valid value for '{k}'")

def setup(self):
"""Setup."""
Expand Down
4 changes: 2 additions & 2 deletions pyspelling/filters/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ def validate_options(self, k, v):

super().validate_options(k, v)
if k == 'errors' and v.lower() not in ('strict', 'replace', 'ignore', 'backslashreplace'):
raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
raise ValueError(f"{self.__class__.__name}: '{v}' is not a valid value for '{k}'")
if k == 'normalize' and v.upper() not in ('NFC', 'NFKC', 'NFD', 'NFKD'):
raise ValueError("{}: '{}' is not a valid value for '{}'".format(self.__class__.__name, v, k))
raise ValueError(f"{self.__class__.__name}: '{v}' is not a valid value for '{k}'")

def setup(self):
"""Setup."""
Expand Down
4 changes: 2 additions & 2 deletions pyspelling/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def __init__(self, options):
self.config = self.get_default_config()
if self.config is None:
warnings.warn(
"'{}' did not provide a default config. ".format(self.__class__.__name__) +
f"'{self.__class__.__name__}' did not provide a default config. " +
"All plugins in the future should provide a default config.",
category=FutureWarning,
stacklevel=1
Expand All @@ -36,7 +36,7 @@ def override_config(self, options):
for k, v in options.items():
# Reject names not in the default configuration
if k not in self.config:
raise KeyError("'{}' is not a valid option for '{}'".format(k, self.__class__.__name__))
raise KeyError(f"'{k}' is not a valid option for '{self.__class__.__name__}'")
self.validate_options(k, v)
self.config[k] = v

Expand Down
2 changes: 1 addition & 1 deletion pyspelling/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def deprecated_func(*args, **kwargs):
"""Display deprecation warning."""

warnings.warn(
"'{}' is deprecated. {}".format(func.__name__, message),
f"'{func.__name__}' is deprecated. {message}",
category=DeprecationWarning,
stacklevel=2
)
Expand Down
12 changes: 6 additions & 6 deletions tests/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

# Disambiguate `TESTFN` for parallel testing, while letting it remain a valid
# module name.
TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())
TESTFN = f"{TESTFN}_{os.getpid()}_tmp"


def which(executable):
Expand Down Expand Up @@ -121,13 +121,13 @@ def assert_spell_required(self, running):
required = os.environ.get("TOX_SPELL_REQUIRE", "any")

if required not in ("both", "any", "aspell", "hunspell"):
raise RuntimeError("Invalid value of '{}' in 'TOX_SPELL_REQUIRE'".format(required))
raise RuntimeError(f"Invalid value of '{required}' in 'TOX_SPELL_REQUIRE'")

if running not in ("both", "aspell", "hunspell"):
raise RuntimeError(
"Required tests are not being run (currently running '{}'). ".format(running) +
f"Required tests are not being run (currently running '{running}'). " +
"Make sure spell checker can be found and " +
"'TOX_SPELL_REQUIRE' is set appropriately (currently '{}')".format(required)
f"'TOX_SPELL_REQUIRE' is set appropriately (currently '{required}')"
)

if required != running and (required != "any" and running != "both"):
Expand Down Expand Up @@ -166,7 +166,7 @@ def assert_context(self, config_file, expected, names=None, groups=None, sources
if results.error:
print(results.error)
context.append(results.context)
self.assertEqual([('{}/{}'.format(self.tempdir, i) if i else i) for i in expected[:]], context)
self.assertEqual([(f'{self.tempdir}/{i}' if i else i) for i in expected[:]], context)
if aspell_location:
context = []
for results in spellcheck(
Expand All @@ -182,7 +182,7 @@ def assert_context(self, config_file, expected, names=None, groups=None, sources
if results.error:
print(results.error)
context.append(results.context)
self.assertEqual([('{}/{}'.format(self.tempdir, i) if i else i) for i in expected[:]], context)
self.assertEqual([(f'{self.tempdir}/{i}' if i else i) for i in expected[:]], context)

def assert_spellcheck(self, config_file, expected, names=None, groups=None, sources=None, verbose=4):
"""Spell check."""
Expand Down

0 comments on commit c05e0fe

Please sign in to comment.