summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorptmcg <ptmcg@austin.rr.com>2022-05-30 18:00:37 -0500
committerptmcg <ptmcg@austin.rr.com>2022-05-30 18:00:37 -0500
commitb89e92442a0140aa694f8f3bd5eea9fe83b552b5 (patch)
treea4a99e00e271c5213c9a6d583dd4f09d6f2b614e
parent48168419f460287ab410bf3370a6828de9d837bb (diff)
downloadpyparsing-git-b89e92442a0140aa694f8f3bd5eea9fe83b552b5.tar.gz
Convert most str.format() calls to use f-strings
-rw-r--r--pyparsing/__init__.py18
-rw-r--r--pyparsing/actions.py8
-rw-r--r--pyparsing/core.py198
-rw-r--r--pyparsing/exceptions.py16
-rw-r--r--pyparsing/helpers.py19
-rw-r--r--pyparsing/results.py13
-rw-r--r--pyparsing/testing.py11
-rw-r--r--pyparsing/util.py14
8 files changed, 103 insertions, 194 deletions
diff --git a/pyparsing/__init__.py b/pyparsing/__init__.py
index e10a1a1..3d69f2a 100644
--- a/pyparsing/__init__.py
+++ b/pyparsing/__init__.py
@@ -106,30 +106,22 @@ class version_info(NamedTuple):
@property
def __version__(self):
return (
- "{}.{}.{}".format(self.major, self.minor, self.micro)
+ f"{self.major}.{self.minor}.{self.micro}"
+ (
- "{}{}{}".format(
- "r" if self.releaselevel[0] == "c" else "",
- self.releaselevel[0],
- self.serial,
- ),
+ f"{'r' if self.releaselevel[0] == 'c' else ''}{self.releaselevel[0]}{self.serial}",
"",
)[self.releaselevel == "final"]
)
def __str__(self):
- return "{} {} / {}".format(__name__, self.__version__, __version_time__)
+ return f"{__name__} {self.__version__} / {__version_time__}"
def __repr__(self):
- return "{}.{}({})".format(
- __name__,
- type(self).__name__,
- ", ".join("{}={!r}".format(*nv) for nv in zip(self._fields, self)),
- )
+ return f"{__name__}.{type(self).__name__}({', '.join('{}={!r}'.format(*nv) for nv in zip(self._fields, self))})"
__version_info__ = version_info(3, 0, 10, "final", 0)
-__version_time__ = "30 May 2022 01:16 UTC"
+__version_time__ = "30 May 2022 23:00 UTC"
__version__ = __version_info__.__version__
__versionTime__ = __version_time__
__author__ = "Paul McGuire <ptmcg.gm+pyparsing@gmail.com>"
diff --git a/pyparsing/actions.py b/pyparsing/actions.py
index 4808c84..8a91e1a 100644
--- a/pyparsing/actions.py
+++ b/pyparsing/actions.py
@@ -38,7 +38,7 @@ def match_only_at_col(n):
def verify_col(strg, locn, toks):
if col(locn, strg) != n:
- raise ParseException(strg, locn, "matched token not at column {}".format(n))
+ raise ParseException(strg, locn, f"matched token not at column {n}")
return verify_col
@@ -148,9 +148,7 @@ def with_attribute(*args, **attr_dict):
raise ParseException(
s,
l,
- "attribute {!r} has value {!r}, must be {!r}".format(
- attrName, tokens[attrName], attrValue
- ),
+ f"attribute {attrName!r} has value {tokens[attrName]!r}, must be {attrValue!r}",
)
return pa
@@ -195,7 +193,7 @@ def with_class(classname, namespace=""):
1 4 0 1 0
1,3 2,3 1,1
"""
- classattr = "{}:class".format(namespace) if namespace else "class"
+ classattr = f"{namespace}:class" if namespace else "class"
return with_attribute(**{classattr: classname})
diff --git a/pyparsing/core.py b/pyparsing/core.py
index 53af6e4..fd7fd69 100644
--- a/pyparsing/core.py
+++ b/pyparsing/core.py
@@ -355,15 +355,9 @@ def _default_start_debug_action(
cache_hit_str = "*" if cache_hit else ""
print(
(
- "{}Match {} at loc {}({},{})\n {}\n {}^".format(
- cache_hit_str,
- expr,
- loc,
- lineno(loc, instring),
- col(loc, instring),
- line(loc, instring),
- " " * (col(loc, instring) - 1),
- )
+ f"{cache_hit_str}Match {expr} at loc {loc}({lineno(loc, instring)},{col(loc, instring)})\n"
+ f" {line(loc, instring)}\n"
+ f" {' ' * (col(loc, instring) - 1)}^"
)
)
@@ -377,7 +371,7 @@ def _default_success_debug_action(
cache_hit: bool = False,
):
cache_hit_str = "*" if cache_hit else ""
- print("{}Matched {} -> {}".format(cache_hit_str, expr, toks.as_list()))
+ print(f"{cache_hit_str}Matched {expr} -> {toks.as_list()}")
def _default_exception_debug_action(
@@ -388,11 +382,7 @@ def _default_exception_debug_action(
cache_hit: bool = False,
):
cache_hit_str = "*" if cache_hit else ""
- print(
- "{}Match {} failed, {} raised: {}".format(
- cache_hit_str, expr, type(exc).__name__, exc
- )
- )
+ print(f"{cache_hit_str}Match {expr} failed, {type(exc).__name__} raised: {exc}")
def null_debug_action(*args):
@@ -1385,9 +1375,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return And([self, other])
@@ -1402,9 +1390,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return other + self
@@ -1416,9 +1402,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return self + And._ErrorStop() + other
@@ -1430,9 +1414,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return other - self
@@ -1480,15 +1462,11 @@ class ParserElement(ABC):
optElements -= minElements
else:
raise TypeError(
- "cannot multiply ParserElement and ({}) objects".format(
- ",".join(type(item).__name__ for item in other)
- )
+ f"cannot multiply ParserElement and ({','.join(type(item).__name__ for item in other)}) objects"
)
else:
raise TypeError(
- "cannot multiply ParserElement and {} objects".format(
- type(other).__name__
- )
+ f"cannot multiply ParserElement and {type(other).__name__} objects"
)
if minElements < 0:
@@ -1536,9 +1514,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return MatchFirst([self, other])
@@ -1550,9 +1526,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return other | self
@@ -1564,9 +1538,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return Or([self, other])
@@ -1578,9 +1550,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return other ^ self
@@ -1592,9 +1562,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return Each([self, other])
@@ -1606,9 +1574,7 @@ class ParserElement(ABC):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
raise TypeError(
- "Cannot combine element of type {} with ParserElement".format(
- type(other).__name__
- )
+ f"Cannot combine element of type {type(other).__name__} with ParserElement"
)
return other & self
@@ -1670,9 +1636,7 @@ class ParserElement(ABC):
if len(key) > 2:
raise TypeError(
- "only 1 or 2 index arguments supported ({}{})".format(
- key[:5], "... [{}]".format(len(key)) if len(key) > 5 else ""
- )
+ f"only 1 or 2 index arguments supported ({key[:5]}{f'... [{len(key)}]' if len(key) > 5 else ''})"
)
# clip to 2 elements
@@ -2131,7 +2095,7 @@ class ParserElement(ABC):
success = success and failureTests
result = pe
except Exception as exc:
- out.append("FAIL-EXCEPTION: {}: {}".format(type(exc).__name__, exc))
+ out.append(f"FAIL-EXCEPTION: {type(exc).__name__}: {exc}")
if ParserElement.verbose_stacktrace:
out.extend(traceback.format_tb(exc.__traceback__))
success = success and failureTests
@@ -2151,9 +2115,7 @@ class ParserElement(ABC):
except Exception as e:
out.append(result.dump(full=fullDump))
out.append(
- "{} failed: {}: {}".format(
- postParse.__name__, type(e).__name__, e
- )
+ f"{postParse.__name__} failed: {type(e).__name__}: {e}"
)
else:
out.append(result.dump(full=fullDump))
@@ -2432,7 +2394,7 @@ class Keyword(Token):
self.firstMatchChar = match_string[0]
except IndexError:
raise ValueError("null string passed to Keyword; use Empty() instead")
- self.errmsg = "Expected {} {}".format(type(self).__name__, self.name)
+ self.errmsg = f"Expected {type(self).__name__} {self.name}"
self.mayReturnEmpty = False
self.mayIndexError = False
self.caseless = caseless
@@ -2600,15 +2562,13 @@ class CloseMatch(Token):
super().__init__()
self.match_string = match_string
self.maxMismatches = maxMismatches
- self.errmsg = "Expected {!r} (with up to {} mismatches)".format(
- self.match_string, self.maxMismatches
- )
+ self.errmsg = f"Expected {self.match_string!r} (with up to {self.maxMismatches} mismatches)"
self.caseless = caseless
self.mayIndexError = False
self.mayReturnEmpty = False
def _generateDefaultName(self) -> str:
- return "{}:{!r}".format(type(self).__name__, self.match_string)
+ return f"{type(self).__name__}:{self.match_string!r}"
def parseImpl(self, instring, loc, doActions=True):
start = loc
@@ -2729,9 +2689,7 @@ class Word(Token):
super().__init__()
if not initChars:
raise ValueError(
- "invalid {}, initChars cannot be empty string".format(
- type(self).__name__
- )
+ f"invalid {type(self).__name__}, initChars cannot be empty string"
)
initChars_set = set(initChars)
@@ -2780,22 +2738,19 @@ class Word(Token):
elif max == 1:
repeat = ""
else:
- repeat = "{{{},{}}}".format(
- self.minLen, "" if self.maxLen == _MAX_INT else self.maxLen
- )
- self.reString = "[{}]{}".format(
- _collapse_string_to_ranges(self.initChars),
- repeat,
+ repeat = f"{{{self.minLen},{'' if self.maxLen == _MAX_INT else self.maxLen}}}"
+ self.reString = (
+ f"[{_collapse_string_to_ranges(self.initChars)}]{repeat}"
)
elif len(self.initChars) == 1:
if max == 0:
repeat = "*"
else:
- repeat = "{{0,{}}}".format(max - 1)
- self.reString = "{}[{}]{}".format(
- re.escape(self.initCharsOrig),
- _collapse_string_to_ranges(self.bodyChars),
- repeat,
+ repeat = f"{{0,{max - 1}}}"
+ self.reString = (
+ f"{re.escape(self.initCharsOrig)}"
+ f"[{_collapse_string_to_ranges(self.bodyChars)}]"
+ f"{repeat}"
)
else:
if max == 0:
@@ -2803,14 +2758,14 @@ class Word(Token):
elif max == 2:
repeat = ""
else:
- repeat = "{{0,{}}}".format(max - 1)
- self.reString = "[{}][{}]{}".format(
- _collapse_string_to_ranges(self.initChars),
- _collapse_string_to_ranges(self.bodyChars),
- repeat,
+ repeat = f"{{0,{max - 1}}}"
+ self.reString = (
+ f"[{_collapse_string_to_ranges(self.initChars)}]"
+ f"[{_collapse_string_to_ranges(self.bodyChars)}]"
+ f"{repeat}"
)
if self.asKeyword:
- self.reString = r"\b" + self.reString + r"\b"
+ self.reString = rf"\b{self.reString}\b"
try:
self.re = re.compile(self.reString)
@@ -2830,11 +2785,9 @@ class Word(Token):
return s
if self.initChars != self.bodyChars:
- base = "W:({}, {})".format(
- charsAsStr(self.initChars), charsAsStr(self.bodyChars)
- )
+ base = f"W:({charsAsStr(self.initChars)}, {charsAsStr(self.bodyChars)})"
else:
- base = "W:({})".format(charsAsStr(self.initChars))
+ base = f"W:({charsAsStr(self.initChars)})"
# add length specification
if self.minLen > 1 or self.maxLen != _MAX_INT:
@@ -2842,11 +2795,11 @@ class Word(Token):
if self.minLen == 1:
return base[2:]
else:
- return base + "{{{}}}".format(self.minLen)
+ return base + f"{{{self.minLen}}}"
elif self.maxLen == _MAX_INT:
- return base + "{{{},...}}".format(self.minLen)
+ return base + f"{{{self.minLen},...}}"
else:
- return base + "{{{},{}}}".format(self.minLen, self.maxLen)
+ return base + f"{{{self.minLen},{self.maxLen}}}"
return base
def parseImpl(self, instring, loc, doActions=True):
@@ -2912,9 +2865,9 @@ class Char(_WordRegex):
super().__init__(
charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars
)
- self.reString = "[{}]".format(_collapse_string_to_ranges(self.initChars))
+ self.reString = f"[{_collapse_string_to_ranges(self.initChars)}]"
if asKeyword:
- self.reString = r"\b{}\b".format(self.reString)
+ self.reString = rf"\b{self.reString}\b"
self.re = re.compile(self.reString)
self.re_match = self.re.match
@@ -2998,9 +2951,7 @@ class Regex(Token):
try:
return re.compile(self.pattern, self.flags)
except re.error:
- raise ValueError(
- "invalid pattern ({!r}) passed to Regex".format(self.pattern)
- )
+ raise ValueError(f"invalid pattern ({self.pattern!r}) passed to Regex")
@cached_property
def re_match(self):
@@ -3168,22 +3119,19 @@ class QuotedString(Token):
inner_pattern = ""
if escQuote:
- inner_pattern += r"{}(?:{})".format(sep, re.escape(escQuote))
+ inner_pattern += rf"{sep}(?:{re.escape(escQuote)})"
sep = "|"
if escChar:
- inner_pattern += r"{}(?:{}.)".format(sep, re.escape(escChar))
+ inner_pattern += rf"{sep}(?:{re.escape(escChar)}.)"
sep = "|"
self.escCharReplacePattern = re.escape(self.escChar) + "(.)"
if len(self.endQuoteChar) > 1:
inner_pattern += (
- "{}(?:".format(sep)
+ f"{sep}(?:"
+ "|".join(
- "(?:{}(?!{}))".format(
- re.escape(self.endQuoteChar[:i]),
- re.escape(self.endQuoteChar[i:]),
- )
+ f"(?:{re.escape(self.endQuoteChar[:i])}(?!{re.escape(self.endQuoteChar[i:])}))"
for i in range(len(self.endQuoteChar) - 1, 0, -1)
)
+ ")"
@@ -3192,17 +3140,15 @@ class QuotedString(Token):
if multiline:
self.flags = re.MULTILINE | re.DOTALL
- inner_pattern += r"{}(?:[^{}{}])".format(
- sep,
- _escape_regex_range_chars(self.endQuoteChar[0]),
- (_escape_regex_range_chars(escChar) if escChar is not None else ""),
+ inner_pattern += (
+ rf"{sep}(?:[^{_escape_regex_range_chars(self.endQuoteChar[0])}"
+ rf"{(_escape_regex_range_chars(escChar) if escChar is not None else '')}])"
)
else:
self.flags = 0
- inner_pattern += r"{}(?:[^{}\n\r{}])".format(
- sep,
- _escape_regex_range_chars(self.endQuoteChar[0]),
- (_escape_regex_range_chars(escChar) if escChar is not None else ""),
+ inner_pattern += (
+ rf"{sep}(?:[^{_escape_regex_range_chars(self.endQuoteChar[0])}\n\r"
+ rf"{(_escape_regex_range_chars(escChar) if escChar is not None else '')}])"
)
self.pattern = "".join(
@@ -3220,9 +3166,7 @@ class QuotedString(Token):
self.reString = self.pattern
self.re_match = self.re.match
except re.error:
- raise ValueError(
- "invalid pattern {!r} passed to Regex".format(self.pattern)
- )
+ raise ValueError(f"invalid pattern {self.pattern!r} passed to Regex")
self.errmsg = "Expected " + self.name
self.mayIndexError = False
@@ -3230,11 +3174,9 @@ class QuotedString(Token):
def _generateDefaultName(self) -> str:
if self.quoteChar == self.endQuoteChar and isinstance(self.quoteChar, str_type):
- return "string enclosed in {!r}".format(self.quoteChar)
+ return f"string enclosed in {self.quoteChar!r}"
- return "quoted string, starting with {} ending with {}".format(
- self.quoteChar, self.endQuoteChar
- )
+ return f"quoted string, starting with {self.quoteChar} ending with {self.endQuoteChar}"
def parseImpl(self, instring, loc, doActions=True):
result = (
@@ -3329,9 +3271,9 @@ class CharsNotIn(Token):
def _generateDefaultName(self) -> str:
not_chars_str = _collapse_string_to_ranges(self.notChars)
if len(not_chars_str) > 16:
- return "!W:({}...)".format(self.notChars[: 16 - 3])
+ return f"!W:({self.notChars[: 16 - 3]}...)"
else:
- return "!W:({})".format(self.notChars)
+ return f"!W:({self.notChars})"
def parseImpl(self, instring, loc, doActions=True):
notchars = self.notCharsSet
@@ -3702,7 +3644,7 @@ class ParseExpression(ParserElement):
return self
def _generateDefaultName(self) -> str:
- return "{}:({})".format(self.__class__.__name__, str(self.exprs))
+ return f"{self.__class__.__name__}:({str(self.exprs)})"
def streamline(self) -> ParserElement:
if self.streamlined:
@@ -4359,7 +4301,7 @@ class Each(ParseExpression):
raise ParseException(
instring,
loc,
- "Missing one or more required elements ({})".format(missing),
+ f"Missing one or more required elements ({missing})",
)
# add any unmatched Opts, in case they have default values defined
@@ -4464,7 +4406,7 @@ class ParseElementEnhance(ParserElement):
self._checkRecursion([])
def _generateDefaultName(self) -> str:
- return "{}:({})".format(self.__class__.__name__, str(self.expr))
+ return f"{self.__class__.__name__}:({str(self.expr)})"
ignoreWhitespace = ignore_whitespace
leaveWhitespace = leave_whitespace
@@ -4479,13 +4421,13 @@ class IndentedBlock(ParseElementEnhance):
class _Indent(Empty):
def __init__(self, ref_col: int):
super().__init__()
- self.errmsg = "expected indent at column {}".format(ref_col)
+ self.errmsg = f"expected indent at column {ref_col}"
self.add_condition(lambda s, l, t: col(l, s) == ref_col)
class _IndentGreater(Empty):
def __init__(self, ref_col: int):
super().__init__()
- self.errmsg = "expected indent at column greater than {}".format(ref_col)
+ self.errmsg = f"expected indent at column greater than {ref_col}"
self.add_condition(lambda s, l, t: col(l, s) > ref_col)
def __init__(
@@ -5674,15 +5616,13 @@ def trace_parse_action(f: ParseAction) -> ParseAction:
s, l, t = paArgs[-3:]
if len(paArgs) > 3:
thisFunc = paArgs[0].__class__.__name__ + "." + thisFunc
- sys.stderr.write(
- ">>entering {}(line: {!r}, {}, {!r})\n".format(thisFunc, line(l, s), l, t)
- )
+ sys.stderr.write(f">>entering {thisFunc}(line: {line(l, s)!r}, {l}, {t!r})\n")
try:
ret = f(*paArgs)
except Exception as exc:
- sys.stderr.write("<<leaving {} (exception: {})\n".format(thisFunc, exc))
+ sys.stderr.write(f"<<leaving {thisFunc} (exception: {exc})\n")
raise
- sys.stderr.write("<<leaving {} (ret: {!r})\n".format(thisFunc, ret))
+ sys.stderr.write(f"<<leaving {thisFunc} (ret: {ret!r})\n")
return ret
z.__name__ = f.__name__
diff --git a/pyparsing/exceptions.py b/pyparsing/exceptions.py
index a38447b..31a5711 100644
--- a/pyparsing/exceptions.py
+++ b/pyparsing/exceptions.py
@@ -64,7 +64,7 @@ class ParseBaseException(Exception):
if isinstance(exc, ParseBaseException):
ret.append(exc.line)
ret.append(" " * (exc.column - 1) + "^")
- ret.append("{}: {}".format(type(exc).__name__, exc))
+ ret.append(f"{type(exc).__name__}: {exc}")
if depth > 0:
callers = inspect.getinnerframes(exc.__traceback__, context=depth)
@@ -82,21 +82,19 @@ class ParseBaseException(Exception):
self_type = type(f_self)
ret.append(
- "{}.{} - {}".format(
- self_type.__module__, self_type.__name__, f_self
- )
+ f"{self_type.__module__}.{self_type.__name__} - {f_self}"
)
elif f_self is not None:
self_type = type(f_self)
- ret.append("{}.{}".format(self_type.__module__, self_type.__name__))
+ ret.append(f"{self_type.__module__}.{self_type.__name__}")
else:
code = frm.f_code
if code.co_name in ("wrapper", "<module>"):
continue
- ret.append("{}".format(code.co_name))
+ ret.append(code.co_name)
depth -= 1
if not depth:
@@ -154,9 +152,7 @@ class ParseBaseException(Exception):
foundstr = (", found %r" % found).replace(r"\\", "\\")
else:
foundstr = ""
- return "{}{} (at char {}), (line:{}, col:{})".format(
- self.msg, foundstr, self.loc, self.lineno, self.column
- )
+ return f"{self.msg}{foundstr} (at char {self.loc}), (line:{self.lineno}, col:{self.column})"
def __repr__(self):
return str(self)
@@ -264,4 +260,4 @@ class RecursiveGrammarException(Exception):
self.parseElementTrace = parseElementList
def __str__(self) -> str:
- return "RecursiveGrammarException: {}".format(self.parseElementTrace)
+ return f"RecursiveGrammarException: {self.parseElementTrace}"
diff --git a/pyparsing/helpers.py b/pyparsing/helpers.py
index c1de43e..5cc5893 100644
--- a/pyparsing/helpers.py
+++ b/pyparsing/helpers.py
@@ -41,11 +41,8 @@ def delimited_list(
expr = ParserElement._literalStringClass(expr)
expr = typing.cast(ParserElement, expr)
- dlName = "{expr} [{delim} {expr}]...{end}".format(
- expr=str(expr.copy().streamline()),
- delim=str(delim),
- end=" [{}]".format(str(delim)) if allow_trailing_delim else "",
- )
+ expr_copy = expr.copy().streamline()
+ dlName = f"{expr_copy} [{delim} {expr_copy}]...{f' [{delim}]' if allow_trailing_delim else ''}"
if not combine:
delim = Suppress(delim)
@@ -188,7 +185,7 @@ def match_previous_expr(expr: ParserElement) -> ParserElement:
theseTokens = _flatten(t.as_list())
if theseTokens != matchTokens:
raise ParseException(
- s, l, "Expected {}, found{}".format(matchTokens, theseTokens)
+ s, l, f"Expected {matchTokens}, found{theseTokens}"
)
rep.set_parse_action(must_match_these_tokens, callDuringTry=True)
@@ -294,15 +291,13 @@ def one_of(
try:
if all(len(sym) == 1 for sym in symbols):
# symbols are just single characters, create range regex pattern
- patt = "[{}]".format(
- "".join(_escape_regex_range_chars(sym) for sym in symbols)
- )
+ patt = f"[{''.join(_escape_regex_range_chars(sym) for sym in symbols)}]"
else:
patt = "|".join(re.escape(sym) for sym in symbols)
# wrap with \b word break markers if defining as keywords
if asKeyword:
- patt = r"\b(?:{})\b".format(patt)
+ patt = rf"\b(?:{patt})\b"
ret = Regex(patt, flags=re_flags).set_name(" | ".join(symbols))
@@ -840,9 +835,9 @@ def infix_notation(
"if numterms=3, opExpr must be a tuple or list of two expressions"
)
opExpr1, opExpr2 = opExpr
- term_name = "{}{} term".format(opExpr1, opExpr2)
+ term_name = f"{opExpr1}{opExpr2} term"
else:
- term_name = "{} term".format(opExpr)
+ term_name = f"{opExpr} term"
if not 1 <= arity <= 3:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
diff --git a/pyparsing/results.py b/pyparsing/results.py
index 00c9421..7631832 100644
--- a/pyparsing/results.py
+++ b/pyparsing/results.py
@@ -47,7 +47,7 @@ class ParseResults:
result = date_str.parse_string("1999/12/31")
def test(s, fn=repr):
- print("{} -> {}".format(s, fn(eval(s))))
+ print(f"{s} -> {fn(eval(s))}")
test("list(result)")
test("result[0]")
test("result['month']")
@@ -127,8 +127,7 @@ class ParseResults:
if not isinstance(contained, list):
raise TypeError(
- "{} may only be constructed with a list,"
- " not {}".format(cls.__name__, type(contained).__name__)
+ f"{cls.__name__} may only be constructed with a list, not {type(contained).__name__}"
)
return list.__new__(cls)
@@ -311,9 +310,7 @@ class ParseResults:
if k == "default":
args = (args[0], v)
else:
- raise TypeError(
- "pop() got an unexpected keyword argument {!r}".format(k)
- )
+ raise TypeError(f"pop() got an unexpected keyword argument {k!r}")
if isinstance(args[0], int) or len(args) == 1 or args[0] in self:
index = args[0]
ret = self[index]
@@ -456,7 +453,7 @@ class ParseResults:
return other + self
def __repr__(self) -> str:
- return "{}({!r}, {})".format(type(self).__name__, self._toklist, self.as_dict())
+ return f"{type(self).__name__}({self._toklist!r}, {self.as_dict()})"
def __str__(self) -> str:
return (
@@ -623,7 +620,7 @@ class ParseResults:
for k, v in items:
if out:
out.append(NL)
- out.append("{}{}- {}: ".format(indent, (" " * _depth), k))
+ out.append(f"{indent}{(' ' * _depth)}- {k}: ")
if isinstance(v, ParseResults):
if v:
out.append(
diff --git a/pyparsing/testing.py b/pyparsing/testing.py
index e2dd355..2b0fcf4 100644
--- a/pyparsing/testing.py
+++ b/pyparsing/testing.py
@@ -222,7 +222,7 @@ class pyparsing_test:
)
else:
# warning here maybe?
- print("no validation for {!r}".format(test_string))
+ print(f"no validation for {test_string!r}")
# do this last, in case some specific test results can be reported instead
self.assertTrue(
@@ -304,7 +304,7 @@ class pyparsing_test:
header0 = (
lead
+ "".join(
- "{}{}".format(" " * 99, (i + 1) % 100)
+ f"{' ' * 99}{(i + 1) % 100}"
for i in range(max(max_line_len // 100, 1))
)
+ "\n"
@@ -314,10 +314,7 @@ class pyparsing_test:
header1 = (
header0
+ lead
- + "".join(
- " {}".format((i + 1) % 10)
- for i in range(-(-max_line_len // 10))
- )
+ + "".join(f" {(i + 1) % 10}" for i in range(-(-max_line_len // 10)))
+ "\n"
)
header2 = lead + "1234567890" * (-(-max_line_len // 10)) + "\n"
@@ -325,7 +322,7 @@ class pyparsing_test:
header1
+ header2
+ "\n".join(
- "{:{}d}:{}{}".format(i, lineno_width, line, eol_mark)
+ f"{i:{lineno_width}d}:{line}{eol_mark}"
for i, line in enumerate(s_lines, start=start_line)
)
+ "\n"
diff --git a/pyparsing/util.py b/pyparsing/util.py
index f2b7f6a..47dbf30 100644
--- a/pyparsing/util.py
+++ b/pyparsing/util.py
@@ -20,18 +20,14 @@ class __config_flags:
def _set(cls, dname, value):
if dname in cls._fixed_names:
warnings.warn(
- "{}.{} {} is {} and cannot be overridden".format(
- cls.__name__,
- dname,
- cls._type_desc,
- str(getattr(cls, dname)).upper(),
- )
+ f"{cls.__name__}.{dname} {cls._type_desc} is {str(getattr(cls, dname)).upper()}"
+ f" and cannot be overridden"
)
return
if dname in cls._all_names:
setattr(cls, dname, value)
else:
- raise ValueError("no such {} {!r}".format(cls._type_desc, dname))
+ raise ValueError(f"no such {cls._type_desc} {dname!r}")
enable = classmethod(lambda cls, name: cls._set(name, True))
disable = classmethod(lambda cls, name: cls._set(name, False))
@@ -215,9 +211,7 @@ def _collapse_string_to_ranges(
else:
sep = "" if ord(last) == ord(first) + 1 else "-"
ret.append(
- "{}{}{}".format(
- escape_re_range_char(first), sep, escape_re_range_char(last)
- )
+ f"{escape_re_range_char(first)}{sep}{escape_re_range_char(last)}"
)
else:
ret = [escape_re_range_char(c) for c in s]