Skip to content

Commit

Permalink
Convert legacy string formatting to f-strings; expand on some docstri…
Browse files Browse the repository at this point in the history
…ngs and comments
  • Loading branch information
ptmcg committed Feb 25, 2024
1 parent c19df25 commit 670ba22
Show file tree
Hide file tree
Showing 25 changed files with 135 additions and 146 deletions.
3 changes: 3 additions & 0 deletions CHANGES
Expand Up @@ -36,6 +36,9 @@ Version 3.1.2 - in development

- Some code refactoring to reduce code nesting, PRs submitted by InSync.

- All internal string expressions using '%' string interpolation and `str.format()`
converted to f-strings.


Version 3.1.1 - July, 2023
--------------------------
Expand Down
2 changes: 1 addition & 1 deletion examples/SimpleCalc.py
Expand Up @@ -52,7 +52,7 @@
# elif op[0].isalpha():
# if op in variables:
# return variables[op]
# raise Exception("invalid identifier '%s'" % op)
# raise Exception(f"invalid identifier {op!r}")
# else:
# return float( op )

Expand Down
10 changes: 5 additions & 5 deletions examples/TAP.py
Expand Up @@ -148,15 +148,15 @@ def summary(self, showPassed=False, showAll=False):
testListStr = lambda tl: "[" + ",".join(str(t.num) for t in tl) + "]"
summaryText = []
if showPassed or showAll:
summaryText.append("PASSED: %s" % testListStr(self.passedTests))
summaryText.append(f"PASSED: {testListStr(self.passedTests)}")
if self.failedTests or showAll:
summaryText.append("FAILED: %s" % testListStr(self.failedTests))
summaryText.append(f"FAILED: {testListStr(self.failedTests)}")
if self.skippedTests or showAll:
summaryText.append("SKIPPED: %s" % testListStr(self.skippedTests))
summaryText.append(f"SKIPPED: {testListStr(self.skippedTests)}")
if self.todoTests or showAll:
summaryText.append("TODO: %s" % testListStr(self.todoTests))
summaryText.append(f"TODO: {testListStr(self.todoTests)}")
if self.bonusTests or showAll:
summaryText.append("BONUS: %s" % testListStr(self.bonusTests))
summaryText.append(f"BONUS: {testListStr(self.bonusTests)}")
if self.passedSuite:
summaryText.append("PASSED")
else:
Expand Down
22 changes: 11 additions & 11 deletions examples/adventureEngine.py
Expand Up @@ -76,9 +76,9 @@ def describe(self):
is_form = "are"
else:
is_form = "is"
print("There {} {} here.".format(is_form, enumerate_items(visibleItems)))
print(f"There {is_form} {enumerate_items(visibleItems)} here.")
else:
print("You see %s." % (enumerate_items(visibleItems)))
print(f"You see {enumerate_items(visibleItems)}.")


class Exit(Room):
Expand Down Expand Up @@ -220,7 +220,7 @@ def _do_command(self, player):
else:
print(subj.cantTakeMessage)
else:
print("There is no %s here." % subj)
print(f"There is no {subj} here.")


class DropCommand(Command):
Expand All @@ -239,7 +239,7 @@ def _do_command(self, player):
rm.add_item(subj)
player.drop(subj)
else:
print("You don't have %s." % (a_or_an(subj)))
print(f"You don't have {a_or_an(subj)}.")


class InventoryCommand(Command):
Expand All @@ -251,7 +251,7 @@ def help_description():
return "INVENTORY or INV or I - lists what items you have"

def _do_command(self, player):
print("You have %s." % enumerate_items(player.inv))
print(f"You have {enumerate_items(player.inv)}.")


class LookCommand(Command):
Expand Down Expand Up @@ -340,7 +340,7 @@ def _do_command(self, player):
else:
print("You can't use that here.")
else:
print("There is no %s here to use." % self.subject)
print(f"There is no {self.subject} here to use.")


class OpenCommand(Command):
Expand All @@ -364,7 +364,7 @@ def _do_command(self, player):
else:
print("You can't open that.")
else:
print("There is no %s here to open." % self.subject)
print(f"There is no {self.subject} here to open.")


class CloseCommand(Command):
Expand All @@ -388,7 +388,7 @@ def _do_command(self, player):
else:
print("You can't close that.")
else:
print("There is no %s here to close." % self.subject)
print(f"There is no {self.subject} here to close.")


class QuitCommand(Command):
Expand Down Expand Up @@ -428,7 +428,7 @@ def _do_command(self, player):
QuitCommand,
HelpCommand,
]:
print(" - %s" % cmd.help_description())
print(f" - {cmd.help_description()}")
print()


Expand Down Expand Up @@ -515,7 +515,7 @@ def make_bnf(self):
def validate_item_name(self, s, l, t):
iname = " ".join(t)
if iname not in Item.items:
raise AppParseException(s, l, "No such item '%s'." % iname)
raise AppParseException(s, l, f"No such item '{iname}'.")
return iname

def parse_cmd(self, cmdstr):
Expand Down Expand Up @@ -556,7 +556,7 @@ def moveTo(self, rm):

def take(self, it):
if it.isDeadly:
print("Aaaagh!...., the %s killed me!" % it)
print(f"Aaaagh!...., the {it} killed me!")
self.gameOver = True
else:
self.inv.append(it)
Expand Down
8 changes: 4 additions & 4 deletions examples/apicheck.py
Expand Up @@ -49,12 +49,12 @@ def apiProc(name, numargs):
while 1:
try:
t, s, e = next(api_scanner)
print("found %s on line %d" % (t.procname, lineno(s, test)))
print(f"found {t.procname} on line {lineno(s, test)}")
except ParseSyntaxException as pe:
print("invalid arg count on line", pe.lineno)
print(pe.lineno, ":", pe.line)
print(f"invalid arg count on line {pe.lineno}")
print(f"{pe.lineno} : {pe.line}")
# reset api scanner to start after this exception location
test = "\n" * (pe.lineno - 1) + test[pe.loc + 1 :]
test = "\n" * (pe.lineno - 1) + test[pe.loc + 1:]
api_scanner = apiRef.scanString(test)
except StopIteration:
break
2 changes: 1 addition & 1 deletion examples/btpyparse.py
Expand Up @@ -30,7 +30,7 @@ def __init__(self, name):
self.name = name

def __repr__(self):
return 'Macro("%s")' % self.name
return f'Macro("{self.name}")'

def __eq__(self, other):
return self.name == other.name
Expand Down
2 changes: 1 addition & 1 deletion examples/cpp_enum_parser.py
Expand Up @@ -49,5 +49,5 @@
for entry in item.names:
if entry.value != "":
idx = int(entry.value)
print("%s_%s = %d" % (item.enum.upper(), entry.name.upper(), idx))
print(f"{item.enum.upper()}_{entry.name.upper()} = {idx}")
idx += 1
9 changes: 2 additions & 7 deletions examples/datetime_parse_actions.py
@@ -1,6 +1,6 @@
# parseActions.py
#
# A sample program a parser to match a date string of the form "YYYY/MM/DD",
# A sample parser to match a date string of the form "YYYY/MM/DD",
# and return it as a datetime, or raise an exception if not a valid date.
#
# Copyright 2012, Paul T. McGuire
Expand Down Expand Up @@ -36,12 +36,7 @@ def convert_to_datetime(s, loc, tokens):
# on the integer expression above
return datetime(tokens.year, tokens.month, tokens.day).date()
except Exception as ve:
errmsg = "'%s/%s/%s' is not a valid date, %s" % (
tokens.year,
tokens.month,
tokens.day,
ve,
)
errmsg = f"'{tokens.year}/{tokens.month}/{tokens.day}' is not a valid date, {ve}"
raise pp.ParseException(s, loc, errmsg)


Expand Down
2 changes: 1 addition & 1 deletion examples/delta_time.py
Expand Up @@ -450,7 +450,7 @@ def verify_offset(instring, parsed):
else:
parsed["verify_offset"] = "FAIL"

print("(relative to %s)" % datetime.now())
print(f"(relative to {datetime.now()})")
success, report = time_expression.runTests(tests, postParse=verify_offset)
assert success

Expand Down
7 changes: 4 additions & 3 deletions examples/dfmparse.py
Expand Up @@ -100,7 +100,7 @@ def to_chr(x):
# a single matched pair of quotes around it.
delphi_string = Combine(
OneOrMore(CONCAT | pound_char | unquoted_sglQuotedString), adjacent=False
).setParseAction(lambda s, l, t: "'%s'" % t[0])
).setParseAction(lambda s, l, t: f"'{t[0]}'")

string_value = delphi_string | base16_value

Expand Down Expand Up @@ -219,9 +219,10 @@ def main(testfiles=None, action=printer):
except Exception:
failures.append(f)

nl = "\n"
if failures:
print("\nfailed while processing %s" % ", ".join(failures))
print("\nsucceeded on %d of %d files" % (success, len(testfiles)))
print(f"{nl}failed while processing {', '.join(failures)}")
print(f"{nl}succeeded on {success} of {len(testfiles)} files")

if len(retval) == 1 and len(testfiles) == 1:
# if only one file is parsed, return the parseResults directly
Expand Down
8 changes: 4 additions & 4 deletions examples/gen_ctypes.py
Expand Up @@ -130,7 +130,7 @@ def typeAsCtypes(typestr):
if typestr in typemap:
return typemap[typestr]
if typestr.endswith("*"):
return "POINTER(%s)" % typeAsCtypes(typestr.rstrip(" *"))
return f"POINTER({typeAsCtypes(typestr.rstrip(' *'))})"
return typestr


Expand Down Expand Up @@ -178,7 +178,7 @@ def typeAsCtypes(typestr):
)
)
for udtype in user_defined_types:
print("class %s(Structure): pass" % typemap[udtype])
print(f"class {typemap[udtype]}(Structure): pass")

print()
print("# constant definitions")
Expand All @@ -192,7 +192,7 @@ def typeAsCtypes(typestr):

print("{}.restype = {}".format(prefix, typeAsCtypes(fn.fn_type)))
if fn.varargs:
print("# warning - %s takes variable argument list" % prefix)
print(f"# warning - {prefix} takes variable argument list")
del fn.fn_args[-1]

if fn.fn_args.asList() != [["void"]]:
Expand All @@ -202,4 +202,4 @@ def typeAsCtypes(typestr):
)
)
else:
print("%s.argtypes = ()" % (prefix))
print(f"{prefix}.argtypes = ()")
2 changes: 1 addition & 1 deletion examples/partial_gene_match.py
Expand Up @@ -47,7 +47,7 @@
for t, startLoc, endLoc in searchseq.scanString(g.gene, overlap=True):
if show_header:
# only need to show the header once
print("%s/%s/%s (%d)" % (g.gene_id, g.organism, g.location, g.gene_len))
print(f"{g.gene_id}/{g.organism}/{g.location} ({g.gene_len})")
print("-" * 24)
show_header = False

Expand Down
4 changes: 2 additions & 2 deletions examples/searchparser.py
Expand Up @@ -301,8 +301,8 @@ def Test(self):
print(item)
r = self.Parse(item)
e = self.tests[item]
print("Result: %s" % r)
print("Expect: %s" % e)
print(f"Result: {r}")
print(f"Expect: {e}")
if e == r:
print("Test OK")
else:
Expand Down
4 changes: 2 additions & 2 deletions examples/simpleBool.py
Expand Up @@ -60,8 +60,8 @@ def __init__(self, t):
self.args = t[0][0::2]

def __str__(self) -> str:
sep = " %s " % self.repr_symbol
return "(" + sep.join(map(str, self.args)) + ")"
sep = f" {self.repr_symbol} "
return f"({sep.join(map(str, self.args))})"

def __bool__(self) -> bool:
return self.eval_fn(bool(a) for a in self.args)
Expand Down
16 changes: 8 additions & 8 deletions examples/statemachine/statemachine.py
Expand Up @@ -75,7 +75,7 @@ def expand_state_definition(source, loc, tokens):
baseStateClass = tokens.name
statedef.extend(
[
"class %s(object):" % baseStateClass,
f"class {baseStateClass}(object):",
" def __str__(self):",
" return self.__class__.__name__",
" @classmethod",
Expand Down Expand Up @@ -173,7 +173,7 @@ def expand_named_state_definition(source, loc, tokens):
# define base class for state classes
statedef.extend(
[
"class %s(object):" % baseStateClass,
f"class {baseStateClass}(object):",
" from statemachine import InvalidTransitionException as BaseTransitionException",
" class InvalidTransitionException(BaseTransitionException): pass",
" def __str__(self):",
Expand All @@ -186,10 +186,10 @@ def expand_named_state_definition(source, loc, tokens):
" try:",
" return cls.tnmap[name]()",
" except KeyError:",
" raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
" raise cls.InvalidTransitionException(f'{cls.__name__} does not support transition {name!r}'",
" def __bad_tn(name):",
" def _fn(cls):",
" raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
" raise cls.InvalidTransitionException(f'{cls.__name__} does not support transition {name!r}'",
" _fn.__name__ = name",
" return _fn",
]
Expand All @@ -207,9 +207,9 @@ def expand_named_state_definition(source, loc, tokens):
# define state transition methods for valid transitions from each state
for s in states:
trns = list(fromTo[s].items())
# statedef.append("%s.tnmap = {%s}" % (s, ", ".join("%s:%s" % tn for tn in trns)))
# statedef.append(f"{s}.tnmap = {{{', '.join('%s:%s' % tn for tn in trns)}}}")
statedef.extend(
"{}.{} = classmethod(lambda cls: {}())".format(s, tn_, to_)
f"{s}.{tn_} = classmethod(lambda cls: {to_}())"
for tn_, to_ in trns
)

Expand Down Expand Up @@ -286,8 +286,8 @@ class SuffixImporter:
@classmethod
def trigger_url(cls):
if cls.suffix is None:
raise ValueError("%s.suffix is not set" % cls.__name__)
return "suffix:%s" % cls.suffix
raise ValueError(f"{cls.__name__}.suffix is not set")
return f"suffix:{cls.suffix}"

@classmethod
def register(cls):
Expand Down
2 changes: 1 addition & 1 deletion examples/statemachine/trafficlightstate.pystate
Expand Up @@ -26,7 +26,7 @@ Green.cars_can_go = True
# setup some class level methods
def flash_crosswalk(s):
def flash():
print("%s...%s...%s" % (s, s, s))
print(f"{s}...{s}...{s}")

return flash

Expand Down
2 changes: 1 addition & 1 deletion pyparsing/__init__.py
Expand Up @@ -121,7 +121,7 @@ def __repr__(self):


__version_info__ = version_info(3, 1, 2, "final", 1)
__version_time__ = "02 Oct 2023 03:34 UTC"
__version_time__ = "25 Feb 2024 17:23 UTC"
__version__ = __version_info__.__version__
__versionTime__ = __version_time__
__author__ = "Paul McGuire <ptmcg.gm+pyparsing@gmail.com>"
Expand Down
1 change: 0 additions & 1 deletion pyparsing/actions.py
Expand Up @@ -111,7 +111,6 @@ def with_attribute(*args, **attr_dict):
<div type="graph">1,3 2,3 1,1</div>
<div>this has no type</div>
</div>
'''
div,div_end = make_html_tags("div")
Expand Down

0 comments on commit 670ba22

Please sign in to comment.