summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorJon Dufresne <jon.dufresne@gmail.com>2019-10-24 20:11:14 -0700
committerPaul McGuire <ptmcg@users.noreply.github.com>2019-10-24 22:11:14 -0500
commitf73e2571fb643a2afdde365eeee0fe0f3f4f5300 (patch)
treef9015586cee7efc5e60eee78a8ebcbaa4e9e953d /examples
parent696808023f10207461d7b22dc1d02cbed44e2bfa (diff)
downloadpyparsing-git-f73e2571fb643a2afdde365eeee0fe0f3f4f5300.tar.gz
Use pyupgrade to upgrade the code to use Python3 conventions (#138)
The pyupgrade project is available at https://github.com/asottile/pyupgrade and can be installed through pip. The pyupgrade tool automatically upgrades syntax for newer versions of the language. As pyparsing is now Python 3 only, can apply some cleanups and simplifications. Ran the tool using the following command: $ find . -name \*.py -exec pyupgrade --py3-plus {} \; For now, pyparsing.py was skipped while it is refactored to a package.
Diffstat (limited to 'examples')
-rw-r--r--examples/TAP.py4
-rw-r--r--examples/adventureEngine.py38
-rw-r--r--examples/bigquery_view_parser.py8
-rw-r--r--examples/booleansearchparser.py19
-rw-r--r--examples/btpyparse.py2
-rw-r--r--examples/chemicalFormulas.py11
-rw-r--r--examples/dfmparse.py2
-rw-r--r--examples/eval_arith.py12
-rw-r--r--examples/gen_ctypes.py16
-rw-r--r--examples/getNTPserversNew.py2
-rw-r--r--examples/greetingInGreek.py1
-rw-r--r--examples/greetingInKorean.py1
-rw-r--r--examples/holaMundo.py2
-rw-r--r--examples/invRegex.py30
-rw-r--r--examples/linenoExample.py2
-rw-r--r--examples/nested.py4
-rw-r--r--examples/parsePythonValue.py1
-rw-r--r--examples/protobuf_parser.py2
-rw-r--r--examples/pymicko.py80
-rw-r--r--examples/pythonGrammarParser.py6
-rw-r--r--examples/rangeCheck.py2
-rw-r--r--examples/romanNumerals.py4
-rw-r--r--examples/searchparser.py2
-rw-r--r--examples/sexpParser.py2
-rw-r--r--examples/shapes.py4
-rw-r--r--examples/simpleBool.py6
-rw-r--r--examples/simpleWiki.py2
-rw-r--r--examples/sparser.py10
-rw-r--r--examples/statemachine/libraryBookDemo.py4
-rw-r--r--examples/statemachine/statemachine.py16
-rw-r--r--examples/statemachine/trafficLightDemo.py2
-rw-r--r--examples/statemachine/vending_machine.py6
-rw-r--r--examples/verilogParse.py2
33 files changed, 145 insertions, 160 deletions
diff --git a/examples/TAP.py b/examples/TAP.py
index 18f57fd..cb3afff 100644
--- a/examples/TAP.py
+++ b/examples/TAP.py
@@ -62,7 +62,7 @@ bailLine = Group(Literal("Bail out!")("BAIL") +
tapOutputParser = Optional(Group(plan)("plan") + NL) & \
Group(OneOrMore((testLine|bailLine) + NL))("tests")
-class TAPTest(object):
+class TAPTest:
def __init__(self,results):
self.num = results.testNumber
self.passed = (results.passed=="ok")
@@ -77,7 +77,7 @@ class TAPTest(object):
ret.skipped = True
return ret
-class TAPSummary(object):
+class TAPSummary:
def __init__(self,results):
self.passedTests = []
self.failedTests = []
diff --git a/examples/adventureEngine.py b/examples/adventureEngine.py
index 8dee391..f4ef392 100644
--- a/examples/adventureEngine.py
+++ b/examples/adventureEngine.py
@@ -32,7 +32,7 @@ def enumerateDoors(l):
out.append(l[-1])
return " ".join(out)
-class Room(object):
+class Room:
def __init__(self, desc):
self.desc = desc
self.inv = []
@@ -66,21 +66,21 @@ class Room(object):
is_form = "are"
else:
is_form = "is"
- print("There {0} {1} here.".format(is_form, enumerateItems(visibleItems)))
+ print("There {} {} here.".format(is_form, enumerateItems(visibleItems)))
else:
print("You see %s." % (enumerateItems(visibleItems)))
class Exit(Room):
def __init__(self):
- super(Exit,self).__init__("")
+ super().__init__("")
def enter(self,player):
player.gameOver = True
-class Item(object):
+class Item:
items = {}
def __init__(self, desc):
self.desc = desc
@@ -116,7 +116,7 @@ class Item(object):
class OpenableItem(Item):
def __init__(self, desc, contents=None):
- super(OpenableItem,self).__init__(desc)
+ super().__init__(desc)
self.isOpenable = True
self.isOpened = False
if contents is not None:
@@ -143,7 +143,7 @@ class OpenableItem(Item):
self.desc = self.desc[5:]
-class Command(object):
+class Command:
"Base class for commands"
def __init__(self, verb, verbProg):
self.verb = verb
@@ -163,7 +163,7 @@ class Command(object):
class MoveCommand(Command):
def __init__(self, quals):
- super(MoveCommand,self).__init__("MOVE", "moving")
+ super().__init__("MOVE", "moving")
self.direction = quals.direction[0]
@staticmethod
@@ -189,7 +189,7 @@ class MoveCommand(Command):
class TakeCommand(Command):
def __init__(self, quals):
- super(TakeCommand,self).__init__("TAKE", "taking")
+ super().__init__("TAKE", "taking")
self.subject = quals.item
@staticmethod
@@ -211,7 +211,7 @@ class TakeCommand(Command):
class DropCommand(Command):
def __init__(self, quals):
- super(DropCommand,self).__init__("DROP", "dropping")
+ super().__init__("DROP", "dropping")
self.subject = quals.item
@staticmethod
@@ -229,7 +229,7 @@ class DropCommand(Command):
class InventoryCommand(Command):
def __init__(self, quals):
- super(InventoryCommand,self).__init__("INV", "taking inventory")
+ super().__init__("INV", "taking inventory")
@staticmethod
def helpDescription():
@@ -240,7 +240,7 @@ class InventoryCommand(Command):
class LookCommand(Command):
def __init__(self, quals):
- super(LookCommand,self).__init__("LOOK", "looking")
+ super().__init__("LOOK", "looking")
@staticmethod
def helpDescription():
@@ -251,7 +251,7 @@ class LookCommand(Command):
class DoorsCommand(Command):
def __init__(self, quals):
- super(DoorsCommand,self).__init__("DOORS", "looking for doors")
+ super().__init__("DOORS", "looking for doors")
@staticmethod
def helpDescription():
@@ -276,7 +276,7 @@ class DoorsCommand(Command):
class UseCommand(Command):
def __init__(self, quals):
- super(UseCommand,self).__init__("USE", "using")
+ super().__init__("USE", "using")
self.subject = Item.items[quals.usedObj]
if quals.targetObj:
self.target = Item.items[quals.targetObj]
@@ -300,7 +300,7 @@ class UseCommand(Command):
class OpenCommand(Command):
def __init__(self, quals):
- super(OpenCommand,self).__init__("OPEN", "opening")
+ super().__init__("OPEN", "opening")
self.subject = Item.items[quals.item]
@staticmethod
@@ -323,7 +323,7 @@ class OpenCommand(Command):
class CloseCommand(Command):
def __init__(self, quals):
- super(CloseCommand,self).__init__("CLOSE", "closing")
+ super().__init__("CLOSE", "closing")
self.subject = Item.items[quals.item]
@staticmethod
@@ -346,7 +346,7 @@ class CloseCommand(Command):
class QuitCommand(Command):
def __init__(self, quals):
- super(QuitCommand,self).__init__("QUIT", "quitting")
+ super().__init__("QUIT", "quitting")
@staticmethod
def helpDescription():
@@ -358,7 +358,7 @@ class QuitCommand(Command):
class HelpCommand(Command):
def __init__(self, quals):
- super(HelpCommand,self).__init__("HELP", "helping")
+ super().__init__("HELP", "helping")
@staticmethod
def helpDescription():
@@ -385,7 +385,7 @@ class HelpCommand(Command):
class AppParseException(ParseException):
pass
-class Parser(object):
+class Parser:
def __init__(self):
self.bnf = self.makeBNF()
@@ -469,7 +469,7 @@ class Parser(object):
"???",
"What?" ] ))
-class Player(object):
+class Player:
def __init__(self, name):
self.name = name
self.gameOver = False
diff --git a/examples/bigquery_view_parser.py b/examples/bigquery_view_parser.py
index f66155e..0277a17 100644
--- a/examples/bigquery_view_parser.py
+++ b/examples/bigquery_view_parser.py
@@ -26,10 +26,10 @@ class BigQueryViewParser:
# Table names and alias names might differ by case, but that's not
# relevant- aliases are not case sensitive
lower_aliases = BigQueryViewParser.lowercase_set_of_tuples(with_aliases)
- tables = set([
+ tables = {
x for x in table_identifiers
if not BigQueryViewParser.lowercase_of_tuple(x) in lower_aliases
- ])
+ }
# Table names ARE case sensitive as described at
# https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#case_sensitivity
@@ -48,7 +48,7 @@ class BigQueryViewParser:
@classmethod
def lowercase_set_of_tuples(cls, set_of_tuples):
- return set([BigQueryViewParser.lowercase_of_tuple(x) for x in set_of_tuples])
+ return {BigQueryViewParser.lowercase_of_tuple(x) for x in set_of_tuples}
@classmethod
def _get_parser(cls):
@@ -311,7 +311,7 @@ class BigQueryViewParser:
case_when = WHEN + expr.copy()("when")
case_then = THEN + expr.copy()("then")
- case_clauses = Group(ZeroOrMore((case_when + case_then)))
+ case_clauses = Group(ZeroOrMore(case_when + case_then))
case_else = ELSE + expr.copy()("else")
case_stmt = (
CASE
diff --git a/examples/booleansearchparser.py b/examples/booleansearchparser.py
index 48456a2..d970e98 100644
--- a/examples/booleansearchparser.py
+++ b/examples/booleansearchparser.py
@@ -1,5 +1,3 @@
-#-*- coding: utf-8 -*-
-# vim:fileencoding=utf-8
"""
Boolean Search query parser (Based on searchparser: https://github.com/pyparsing/pyparsing/blob/master/examples/searchparser.py)
@@ -83,7 +81,6 @@ TODO:
- add more kinds of wildcards ('*' at the beginning and '*' inside a word)?
"""
-from __future__ import print_function
from pyparsing import Word, alphanums, Keyword, Group, Forward, Suppress, OneOrMore, oneOf
import re
@@ -146,7 +143,7 @@ class BooleanSearchParser:
#suport for non-western alphabets
for r in alphabet_ranges:
- alphabet += u''.join(chr(c) for c in range(*r) if not chr(c).isspace())
+ alphabet += ''.join(chr(c) for c in range(*r) if not chr(c).isspace())
operatorWord = Group(
Word(alphabet + '*')
@@ -163,7 +160,7 @@ class BooleanSearchParser:
).setResultsName("quotes") | operatorWord
operatorParenthesis = Group(
- (Suppress("(") + operatorOr + Suppress(")"))
+ Suppress("(") + operatorOr + Suppress(")")
).setResultsName("parenthesis") | operatorQuotes
operatorNot = Forward()
@@ -216,14 +213,14 @@ class BooleanSearchParser:
return self.GetQuotes(' '.join(search_terms), r)
def evaluateWord(self, argument):
- wildcard_count = argument[0].count(u"*")
+ wildcard_count = argument[0].count("*")
if wildcard_count > 0:
- if wildcard_count == 1 and argument[0].startswith(u"*"):
+ if wildcard_count == 1 and argument[0].startswith("*"):
return self.GetWordWildcard(argument[0][1:], method = "endswith")
- if wildcard_count == 1 and argument[0].endswith(u"*"):
+ if wildcard_count == 1 and argument[0].endswith("*"):
return self.GetWordWildcard(argument[0][:-1], method = "startswith")
else:
- _regex = argument[0].replace(u"*",u".+")
+ _regex = argument[0].replace("*",".+")
matched = False
for w in self.words:
matched = bool(re.search(_regex,w))
@@ -343,7 +340,7 @@ class ParserTest(BooleanSearchParser):
'32': 'help hilp not holp',
'33': 'help hilp and not holp',
'34': '*lp and halp',
- '35': u'*신은 and 어떠세요',
+ '35': '*신은 and 어떠세요',
}
texts_matcheswith = {
@@ -371,7 +368,7 @@ class ParserTest(BooleanSearchParser):
"nothing": [
"25", "10", "12"
],
- u"안녕하세요, 당신은 어떠세요?": [
+ "안녕하세요, 당신은 어떠세요?": [
"10", "12", "25", "35"
]
}
diff --git a/examples/btpyparse.py b/examples/btpyparse.py
index 1d8992b..39e5261 100644
--- a/examples/btpyparse.py
+++ b/examples/btpyparse.py
@@ -14,7 +14,7 @@ from pyparsing import (Regex, Suppress, ZeroOrMore, Group, Optional, Forward,
SkipTo, CaselessLiteral, Dict)
-class Macro(object):
+class Macro:
""" Class to encapsulate undefined macro references """
def __init__(self, name):
self.name = name
diff --git a/examples/chemicalFormulas.py b/examples/chemicalFormulas.py
index 753901b..1b41871 100644
--- a/examples/chemicalFormulas.py
+++ b/examples/chemicalFormulas.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
#
# chemicalFormulas.py
#
@@ -33,7 +32,7 @@ formula.runTests("""\
C6H5OH
NaCl
""",
- fullDump=False, postParse=lambda _, tokens: "Molecular weight: {0}".format(fn(tokens)))
+ fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format(fn(tokens)))
print()
# Version 2 - access parsed items by results name
@@ -46,7 +45,7 @@ formula.runTests("""\
C6H5OH
NaCl
""",
- fullDump=False, postParse=lambda _, tokens: "Molecular weight: {0}".format(fn(tokens)))
+ fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format(fn(tokens)))
print()
# Version 3 - convert integers during parsing process
@@ -60,12 +59,12 @@ formula.runTests("""\
C6H5OH
NaCl
""",
- fullDump=False, postParse=lambda _, tokens: "Molecular weight: {0}".format(fn(tokens)))
+ fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format(fn(tokens)))
print()
# Version 4 - parse and convert integers as subscript digits
subscript_digits = "₀₁₂₃₄₅₆₇₈₉"
-subscript_int_map = dict((e[1], e[0]) for e in enumerate(subscript_digits))
+subscript_int_map = {e[1]: e[0] for e in enumerate(subscript_digits)}
def cvt_subscript_int(s):
ret = 0
for c in s[0]:
@@ -80,5 +79,5 @@ formula.runTests("""\
C₆H₅OH
NaCl
""",
- fullDump=False, postParse=lambda _, tokens: "Molecular weight: {0}".format(fn(tokens)))
+ fullDump=False, postParse=lambda _, tokens: "Molecular weight: {}".format(fn(tokens)))
print()
diff --git a/examples/dfmparse.py b/examples/dfmparse.py
index ae74bf0..5a1d2a0 100644
--- a/examples/dfmparse.py
+++ b/examples/dfmparse.py
@@ -109,7 +109,7 @@ attribute_value_pair << Group(
| generic_attribute_value_pair
)
-object_declaration = Group((OBJECT + object_name + COLON + object_type))
+object_declaration = Group(OBJECT + object_name + COLON + object_type)
object_attributes = Group(ZeroOrMore(attribute_value_pair))
nested_object = Forward()
diff --git a/examples/eval_arith.py b/examples/eval_arith.py
index 0896c01..8f3e996 100644
--- a/examples/eval_arith.py
+++ b/examples/eval_arith.py
@@ -11,7 +11,7 @@
from pyparsing import Word, nums, alphas, Combine, oneOf, \
opAssoc, infixNotation, Literal
-class EvalConstant(object):
+class EvalConstant:
"Class to evaluate a parsed constant or variable"
vars_ = {}
def __init__(self, tokens):
@@ -22,7 +22,7 @@ class EvalConstant(object):
else:
return float(self.value)
-class EvalSignOp(object):
+class EvalSignOp:
"Class to evaluate expressions with a leading + or - sign"
def __init__(self, tokens):
self.sign, self.value = tokens[0]
@@ -39,7 +39,7 @@ def operatorOperands(tokenlist):
except StopIteration:
break
-class EvalPowerOp(object):
+class EvalPowerOp:
"Class to evaluate multiplication and division expressions"
def __init__(self, tokens):
self.value = tokens[0]
@@ -49,7 +49,7 @@ class EvalPowerOp(object):
res = val.eval()**res
return res
-class EvalMultOp(object):
+class EvalMultOp:
"Class to evaluate multiplication and division expressions"
def __init__(self, tokens):
self.value = tokens[0]
@@ -62,7 +62,7 @@ class EvalMultOp(object):
prod /= val.eval()
return prod
-class EvalAddOp(object):
+class EvalAddOp:
"Class to evaluate addition and subtraction expressions"
def __init__(self, tokens):
self.value = tokens[0]
@@ -75,7 +75,7 @@ class EvalAddOp(object):
sum -= val.eval()
return sum
-class EvalComparisonOp(object):
+class EvalComparisonOp:
"Class to evaluate comparison expressions"
opMap = {
"<" : lambda a,b : a < b,
diff --git a/examples/gen_ctypes.py b/examples/gen_ctypes.py
index f4a8756..325aa28 100644
--- a/examples/gen_ctypes.py
+++ b/examples/gen_ctypes.py
@@ -102,7 +102,7 @@ def getUDType(typestr):
key = typestr.rstrip(" *")
if key not in typemap:
user_defined_types.add(key)
- typemap[key] = "{0}_{1}".format(module, key)
+ typemap[key] = "{}_{}".format(module, key)
def typeAsCtypes(typestr):
if typestr in typemap:
@@ -140,13 +140,13 @@ for en_,_,_ in enum_def.scanString(c_header):
enum_constants.append( (ev.name, ev.value) )
print("from ctypes import *")
-print("{0} = CDLL('{1}.dll')".format(module, module))
+print("{} = CDLL('{}.dll')".format(module, module))
print()
print("# user defined types")
for tdname,tdtyp in typedefs:
- print("{0} = {1}".format(tdname, typemap[tdtyp]))
+ print("{} = {}".format(tdname, typemap[tdtyp]))
for fntd in fn_typedefs:
- print("{0} = CFUNCTYPE({1})".format(fntd.fn_name,
+ print("{} = CFUNCTYPE({})".format(fntd.fn_name,
',\n '.join(typeAsCtypes(a.argtype) for a in fntd.fn_args)))
for udtype in user_defined_types:
print("class %s(Structure): pass" % typemap[udtype])
@@ -154,19 +154,19 @@ for udtype in user_defined_types:
print()
print("# constant definitions")
for en,ev in enum_constants:
- print("{0} = {1}".format(en,ev))
+ print("{} = {}".format(en,ev))
print()
print("# functions")
for fn in functions:
- prefix = "{0}.{1}".format(module, fn.fn_name)
+ prefix = "{}.{}".format(module, fn.fn_name)
- print("{0}.restype = {1}".format(prefix, typeAsCtypes(fn.fn_type)))
+ print("{}.restype = {}".format(prefix, typeAsCtypes(fn.fn_type)))
if fn.varargs:
print("# warning - %s takes variable argument list" % prefix)
del fn.fn_args[-1]
if fn.fn_args.asList() != [['void']]:
- print("{0}.argtypes = ({1},)".format(prefix, ','.join(typeAsCtypes(a.argtype) for a in fn.fn_args)))
+ print("{}.argtypes = ({},)".format(prefix, ','.join(typeAsCtypes(a.argtype) for a in fn.fn_args)))
else:
print("%s.argtypes = ()" % (prefix))
diff --git a/examples/getNTPserversNew.py b/examples/getNTPserversNew.py
index af47c73..3ee5e06 100644
--- a/examples/getNTPserversNew.py
+++ b/examples/getNTPserversNew.py
@@ -25,5 +25,5 @@ with urlopen(nistTimeServerURL) as serverListPage:
addrs = {}
for srvr, startloc, endloc in timeServerPattern.scanString(serverListHTML):
- print("{0} ({1}) - {2}".format(srvr.ipAddr, srvr.hostname.strip(), srvr.loc.strip()))
+ print("{} ({}) - {}".format(srvr.ipAddr, srvr.hostname.strip(), srvr.loc.strip()))
addrs[srvr.ipAddr] = srvr.loc
diff --git a/examples/greetingInGreek.py b/examples/greetingInGreek.py
index 8d20c36..56117d2 100644
--- a/examples/greetingInGreek.py
+++ b/examples/greetingInGreek.py
@@ -1,4 +1,3 @@
-# vim:fileencoding=utf-8
#
# greetingInGreek.py
#
diff --git a/examples/greetingInKorean.py b/examples/greetingInKorean.py
index 8b6fa49..9e881ac 100644
--- a/examples/greetingInKorean.py
+++ b/examples/greetingInKorean.py
@@ -1,4 +1,3 @@
-# vim:fileencoding=utf-8
#
# greetingInKorean.py
#
diff --git a/examples/holaMundo.py b/examples/holaMundo.py
index 2773a34..02be601 100644
--- a/examples/holaMundo.py
+++ b/examples/holaMundo.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
# escrito por Marco Alfonso, 2004 Noviembre
# importamos los símbolos requeridos desde el módulo
diff --git a/examples/invRegex.py b/examples/invRegex.py
index e935b3b..1777635 100644
--- a/examples/invRegex.py
+++ b/examples/invRegex.py
@@ -17,7 +17,7 @@ from pyparsing import (Literal, oneOf, printables, ParserElement, Combine,
SkipTo, infixNotation, ParseFatalException, Word, nums, opAssoc,
Suppress, ParseResults, srange)
-class CharacterRangeEmitter(object):
+class CharacterRangeEmitter:
def __init__(self,chars):
# remove duplicate chars in character range, but preserve original order
seen = set()
@@ -28,56 +28,50 @@ class CharacterRangeEmitter(object):
return '['+self.charset+']'
def makeGenerator(self):
def genChars():
- for s in self.charset:
- yield s
+ yield from self.charset
return genChars
-class OptionalEmitter(object):
+class OptionalEmitter:
def __init__(self,expr):
self.expr = expr
def makeGenerator(self):
def optionalGen():
yield ""
- for s in self.expr.makeGenerator()():
- yield s
+ yield from self.expr.makeGenerator()()
return optionalGen
-class DotEmitter(object):
+class DotEmitter:
def makeGenerator(self):
def dotGen():
- for c in printables:
- yield c
+ yield from printables
return dotGen
-class GroupEmitter(object):
+class GroupEmitter:
def __init__(self,exprs):
self.exprs = ParseResults(exprs)
def makeGenerator(self):
def groupGen():
def recurseList(elist):
if len(elist)==1:
- for s in elist[0].makeGenerator()():
- yield s
+ yield from elist[0].makeGenerator()()
else:
for s in elist[0].makeGenerator()():
for s2 in recurseList(elist[1:]):
yield s + s2
if self.exprs:
- for s in recurseList(self.exprs):
- yield s
+ yield from recurseList(self.exprs)
return groupGen
-class AlternativeEmitter(object):
+class AlternativeEmitter:
def __init__(self,exprs):
self.exprs = exprs
def makeGenerator(self):
def altGen():
for e in self.exprs:
- for s in e.makeGenerator()():
- yield s
+ yield from e.makeGenerator()()
return altGen
-class LiteralEmitter(object):
+class LiteralEmitter:
def __init__(self,lit):
self.lit = lit
def __str__(self):
diff --git a/examples/linenoExample.py b/examples/linenoExample.py
index 0f84e10..f343869 100644
--- a/examples/linenoExample.py
+++ b/examples/linenoExample.py
@@ -30,7 +30,7 @@ OneOrMore(wd).parseString(data)
# demonstrate returning an object from a parse action, containing more information
# than just the matching token text
-class Token(object):
+class Token:
def __init__(self, st, locn, tokString):
self.tokenString = tokString
self.locn = locn
diff --git a/examples/nested.py b/examples/nested.py
index 2e71d62..218c10b 100644
--- a/examples/nested.py
+++ b/examples/nested.py
@@ -21,8 +21,8 @@ data = """
# use {}'s for nested lists
nestedItems = nestedExpr("{", "}")
-print(( (nestedItems+stringEnd).parseString(data).asList() ))
+print( (nestedItems+stringEnd).parseString(data).asList() )
# use default delimiters of ()'s
mathExpr = nestedExpr()
-print(( mathExpr.parseString( "((( ax + by)*C) *(Z | (E^F) & D))") ))
+print( mathExpr.parseString( "((( ax + by)*C) *(Z | (E^F) & D))") )
diff --git a/examples/parsePythonValue.py b/examples/parsePythonValue.py
index cdfac70..259473f 100644
--- a/examples/parsePythonValue.py
+++ b/examples/parsePythonValue.py
@@ -2,7 +2,6 @@
#
# Copyright, 2006, by Paul McGuire
#
-from __future__ import print_function
import pyparsing as pp
diff --git a/examples/protobuf_parser.py b/examples/protobuf_parser.py
index e1657b4..ae5b5d3 100644
--- a/examples/protobuf_parser.py
+++ b/examples/protobuf_parser.py
@@ -17,7 +17,7 @@ LBRACE,RBRACE,LBRACK,RBRACK,LPAR,RPAR,EQ,SEMI = map(Suppress,"{}[]()=;")
kwds = """message required optional repeated enum extensions extends extend
to package service rpc returns true false option import syntax"""
for kw in kwds.split():
- exec("{0}_ = Keyword('{1}')".format(kw.upper(), kw))
+ exec("{}_ = Keyword('{}')".format(kw.upper(), kw))
messageBody = Forward()
diff --git a/examples/pymicko.py b/examples/pymicko.py
index 7dcdf69..eddfdd3 100644
--- a/examples/pymicko.py
+++ b/examples/pymicko.py
@@ -211,7 +211,7 @@ class Enumerate(dict):
setattr(self, name, number)
self[number] = name
-class SharedData(object):
+class SharedData:
"""Data used in all three main classes"""
#Possible kinds of symbol table entries
@@ -247,7 +247,7 @@ class SharedData(object):
##########################################################################################
##########################################################################################
-class ExceptionSharedData(object):
+class ExceptionSharedData:
"""Class for exception handling data"""
def __init__(self):
@@ -270,7 +270,7 @@ class SemanticException(Exception):
"""
def __init__(self, message, print_location=True):
- super(SemanticException,self).__init__()
+ super().__init__()
self._message = message
self.location = exshared.location
self.print_location = print_location
@@ -300,7 +300,7 @@ class SemanticException(Exception):
##########################################################################################
##########################################################################################
-class SymbolTableEntry(object):
+class SymbolTableEntry:
"""Class which represents one symbol table entry."""
def __init__(self, sname = "", skind = 0, stype = 0, sattr = None, sattr_name = "None"):
@@ -325,9 +325,9 @@ class SymbolTableEntry(object):
def attribute_str(self):
"""Returns attribute string (used only for table display)"""
- return "{0}={1}".format(self.attribute_name, self.attribute) if self.attribute != None else "None"
+ return "{}={}".format(self.attribute_name, self.attribute) if self.attribute != None else "None"
-class SymbolTable(object):
+class SymbolTable:
"""Class for symbol table of microC program"""
def __init__(self, shared):
@@ -368,9 +368,9 @@ class SymbolTable(object):
parameters = ""
for p in sym.param_types:
if parameters == "":
- parameters = "{0}".format(SharedData.TYPES[p])
+ parameters = "{}".format(SharedData.TYPES[p])
else:
- parameters += ", {0}".format(SharedData.TYPES[p])
+ parameters += ", {}".format(SharedData.TYPES[p])
print("{0:3d} | {1:^{2}s} | {3:^{4}s} | {5:^{6}s} | {7:^{8}} | ({9})".format(i, sym.name, sym_len, SharedData.KINDS[sym.kind], kind_len, SharedData.TYPES[sym.type], type_len, sym.attribute_str(), attr_len, parameters))
def insert_symbol(self, sname, skind, stype):
@@ -520,7 +520,7 @@ class SymbolTable(object):
##########################################################################################
##########################################################################################
-class CodeGenerator(object):
+class CodeGenerator:
"""Class for code generation methods."""
#dictionary of relational operators
@@ -604,7 +604,7 @@ class CodeGenerator(object):
internal - boolean value, adds "@" prefix to label
definition - boolean value, adds ":" suffix to label
"""
- return "{0}{1}{2}".format(self.internal if internal else "", name, self.definition if definition else "")
+ return "{}{}{}".format(self.internal if internal else "", name, self.definition if definition else "")
def symbol(self, index):
"""Generates symbol name from index"""
@@ -616,14 +616,14 @@ class CodeGenerator(object):
sym = self.symtab.table[index]
#local variables are located at negative offset from frame pointer register
if sym.kind == SharedData.KINDS.LOCAL_VAR:
- return "-{0}(1:%14)".format(sym.attribute * 4 + 4)
+ return "-{}(1:%14)".format(sym.attribute * 4 + 4)
#parameters are located at positive offset from frame pointer register
elif sym.kind == SharedData.KINDS.PARAMETER:
- return "{0}(1:%14)".format(8 + sym.attribute * 4)
+ return "{}(1:%14)".format(8 + sym.attribute * 4)
elif sym.kind == SharedData.KINDS.CONSTANT:
- return "${0}".format(sym.name)
+ return "${}".format(sym.name)
else:
- return "{0}".format(sym.name)
+ return "{}".format(sym.name)
def save_used_registers(self):
"""Pushes all used working registers before function call"""
@@ -674,7 +674,7 @@ class CodeGenerator(object):
internal - boolean value, adds "@" prefix to label
definition - boolean value, adds ":" suffix to label
"""
- self.newline_text(self.label("{0}{1}{2}".format("@" if internal else "", name, ":" if definition else "")))
+ self.newline_text(self.label("{}{}{}".format("@" if internal else "", name, ":" if definition else "")))
def global_var(self, name):
"""Inserts a new static (global) variable definition"""
@@ -704,7 +704,7 @@ class CodeGenerator(object):
#if operand3 is not defined, reserve one free register for it
output = self.take_register(output_type) if operand3 == None else operand3
mnemonic = self.arithmetic_mnemonic(operation, output_type)
- self.newline_text("{0}\t{1},{2},{3}".format(mnemonic, self.symbol(operand1), self.symbol(operand2), self.symbol(output)), True)
+ self.newline_text("{}\t{},{},{}".format(mnemonic, self.symbol(operand1), self.symbol(operand2), self.symbol(output)), True)
return output
def relop_code(self, relop, operands_type):
@@ -723,13 +723,13 @@ class CodeGenerator(object):
label - jump label
"""
jump = self.OPPOSITE_JUMPS[relcode] if opposite else self.CONDITIONAL_JUMPS[relcode]
- self.newline_text("{0}\t{1}".format(jump, label), True)
+ self.newline_text("{}\t{}".format(jump, label), True)
def unconditional_jump(self, label):
"""Generates an unconditional jump instruction
label - jump label
"""
- self.newline_text("JMP \t{0}".format(label), True)
+ self.newline_text("JMP \t{}".format(label), True)
def move(self,operand1, operand2):
"""Generates a move instruction
@@ -741,7 +741,7 @@ class CodeGenerator(object):
self.free_if_register(operand1)
else:
output_type = SharedData.TYPES.NO_TYPE
- self.newline_text("MOV \t{0},{1}".format(self.symbol(operand1), self.symbol(operand2)), True)
+ self.newline_text("MOV \t{},{}".format(self.symbol(operand1), self.symbol(operand2)), True)
if isinstance(operand2, int):
if self.symtab.get_kind(operand2) == SharedData.KINDS.WORKING_REGISTER:
self.symtab.set_type(operand2, output_type)
@@ -761,7 +761,7 @@ class CodeGenerator(object):
typ = self.symtab.get_type(operand1)
self.free_if_register(operand1)
self.free_if_register(operand2)
- self.newline_text("CMP{0}\t{1},{2}".format(self.OPSIGNS[typ], self.symbol(operand1), self.symbol(operand2)), True)
+ self.newline_text("CMP{}\t{},{}".format(self.OPSIGNS[typ], self.symbol(operand1), self.symbol(operand2)), True)
def function_begin(self):
"""Inserts function name label and function frame initialization"""
@@ -796,13 +796,13 @@ class CodeGenerator(object):
args = self.symtab.get_attribute(function)
#generates stack cleanup if function has arguments
if args > 0:
- args_space = self.symtab.insert_constant("{0}".format(args * 4), SharedData.TYPES.UNSIGNED)
+ args_space = self.symtab.insert_constant("{}".format(args * 4), SharedData.TYPES.UNSIGNED)
self.arithmetic("+", "%15", args_space, "%15")
##########################################################################################
##########################################################################################
-class MicroC(object):
+class MicroC:
"""Class for microC parser/compiler"""
def __init__(self):
@@ -835,7 +835,7 @@ class MicroC(object):
Group(Suppress("(") + self.rNumExp + Suppress(")")) |
Group("+" + self.rExp) |
Group("-" + self.rExp)).setParseAction(lambda x : x[0])
- self.rMulExp << ((self.rExp + ZeroOrMore(self.tMulOp + self.rExp))).setParseAction(self.mulexp_action)
+ self.rMulExp << (self.rExp + ZeroOrMore(self.tMulOp + self.rExp)).setParseAction(self.mulexp_action)
self.rNumExp << (self.rMulExp + ZeroOrMore(self.tAddOp + self.rMulExp)).setParseAction(self.numexp_action)
#Definitions of rules for logical expressions (these are without parenthesis support)
@@ -1148,7 +1148,7 @@ class MicroC(object):
if DEBUG > 2: return
exshared.setpos(loc, text)
if not self.symtab.same_types(arg[0], arg[2]):
- raise SemanticException("Invalid operands for operator '{0}'".format(arg[1]))
+ raise SemanticException("Invalid operands for operator '{}'".format(arg[1]))
self.codegen.compare(arg[0], arg[2])
#return relational operator's code
self.relexp_code = self.codegen.relop_code(arg[1], self.symtab.get_type(arg[0]))
@@ -1161,7 +1161,7 @@ class MicroC(object):
print("AND+EXP:",arg)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
- label = self.codegen.label("false{0}".format(self.false_label_number), True, False)
+ label = self.codegen.label("false{}".format(self.false_label_number), True, False)
self.codegen.jump(self.relexp_code, True, label)
self.andexp_code = self.relexp_code
return self.andexp_code
@@ -1173,9 +1173,9 @@ class MicroC(object):
print("LOG_EXP:",arg)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
- label = self.codegen.label("true{0}".format(self.label_number), True, False)
+ label = self.codegen.label("true{}".format(self.label_number), True, False)
self.codegen.jump(self.relexp_code, False, label)
- self.codegen.newline_label("false{0}".format(self.false_label_number), True, True)
+ self.codegen.newline_label("false{}".format(self.false_label_number), True, True)
self.false_label_number += 1
def if_begin_action(self, text, loc, arg):
@@ -1187,7 +1187,7 @@ class MicroC(object):
if DEBUG > 2: return
self.false_label_number += 1
self.label_number = self.false_label_number
- self.codegen.newline_label("if{0}".format(self.label_number), True, True)
+ self.codegen.newline_label("if{}".format(self.label_number), True, True)
def if_body_action(self, text, loc, arg):
"""Code executed after recognising if statement's body"""
@@ -1197,10 +1197,10 @@ class MicroC(object):
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
#generate conditional jump (based on last compare)
- label = self.codegen.label("false{0}".format(self.false_label_number), True, False)
+ label = self.codegen.label("false{}".format(self.false_label_number), True, False)
self.codegen.jump(self.relexp_code, True, label)
#generate 'true' label (executes if condition is satisfied)
- self.codegen.newline_label("true{0}".format(self.label_number), True, True)
+ self.codegen.newline_label("true{}".format(self.label_number), True, True)
#save label numbers (needed for nested if/while statements)
self.label_stack.append(self.false_label_number)
self.label_stack.append(self.label_number)
@@ -1214,10 +1214,10 @@ class MicroC(object):
if DEBUG > 2: return
#jump to exit after all statements for true condition are executed
self.label_number = self.label_stack.pop()
- label = self.codegen.label("exit{0}".format(self.label_number), True, False)
+ label = self.codegen.label("exit{}".format(self.label_number), True, False)
self.codegen.unconditional_jump(label)
#generate final 'false' label (executes if condition isn't satisfied)
- self.codegen.newline_label("false{0}".format(self.label_stack.pop()), True, True)
+ self.codegen.newline_label("false{}".format(self.label_stack.pop()), True, True)
self.label_stack.append(self.label_number)
def if_end_action(self, text, loc, arg):
@@ -1227,7 +1227,7 @@ class MicroC(object):
print("IF_END:",arg)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
- self.codegen.newline_label("exit{0}".format(self.label_stack.pop()), True, True)
+ self.codegen.newline_label("exit{}".format(self.label_stack.pop()), True, True)
def while_begin_action(self, text, loc, arg):
"""Code executed after recognising a while statement (while keyword)"""
@@ -1238,7 +1238,7 @@ class MicroC(object):
if DEBUG > 2: return
self.false_label_number += 1
self.label_number = self.false_label_number
- self.codegen.newline_label("while{0}".format(self.label_number), True, True)
+ self.codegen.newline_label("while{}".format(self.label_number), True, True)
def while_body_action(self, text, loc, arg):
"""Code executed after recognising while statement's body"""
@@ -1248,10 +1248,10 @@ class MicroC(object):
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
#generate conditional jump (based on last compare)
- label = self.codegen.label("false{0}".format(self.false_label_number), True, False)
+ label = self.codegen.label("false{}".format(self.false_label_number), True, False)
self.codegen.jump(self.relexp_code, True, label)
#generate 'true' label (executes if condition is satisfied)
- self.codegen.newline_label("true{0}".format(self.label_number), True, True)
+ self.codegen.newline_label("true{}".format(self.label_number), True, True)
self.label_stack.append(self.false_label_number)
self.label_stack.append(self.label_number)
@@ -1264,11 +1264,11 @@ class MicroC(object):
if DEBUG > 2: return
#jump to condition checking after while statement body
self.label_number = self.label_stack.pop()
- label = self.codegen.label("while{0}".format(self.label_number), True, False)
+ label = self.codegen.label("while{}".format(self.label_number), True, False)
self.codegen.unconditional_jump(label)
#generate final 'false' label and exit label
- self.codegen.newline_label("false{0}".format(self.label_stack.pop()), True, True)
- self.codegen.newline_label("exit{0}".format(self.label_number), True, True)
+ self.codegen.newline_label("false{}".format(self.label_stack.pop()), True, True)
+ self.codegen.newline_label("exit{}".format(self.label_number), True, True)
def program_end_action(self, text, loc, arg):
"""Checks if there is a 'main' function and the type of 'main' function"""
@@ -1320,7 +1320,7 @@ if 0:
input_file = argv[1]
output_file = argv[2]
else:
- usage = """Usage: {0} [input_file [output_file]]
+ usage = """Usage: {} [input_file [output_file]]
If output file is omitted, output.asm is used
If input file is omitted, stdin is used""".format(argv[0])
print(usage)
diff --git a/examples/pythonGrammarParser.py b/examples/pythonGrammarParser.py
index 4a8adce..e3685a1 100644
--- a/examples/pythonGrammarParser.py
+++ b/examples/pythonGrammarParser.py
@@ -130,14 +130,14 @@ testlist1: test (',' test)*
encoding_decl: NAME
"""
-class SemanticGroup(object):
+class SemanticGroup:
def __init__(self,contents):
self.contents = contents
while self.contents[-1].__class__ == self.__class__:
self.contents = self.contents[:-1] + self.contents[-1].contents
def __str__(self):
- return "{0}({1})".format(self.label,
+ return "{}({})".format(self.label,
" ".join([isinstance(c,str) and c or str(c) for c in self.contents]) )
class OrList(SemanticGroup):
@@ -164,7 +164,7 @@ class Atom(SemanticGroup):
self.contents = contents[0]
def __str__(self):
- return "{0}{1}".format(self.rep, self.contents)
+ return "{}{}".format(self.rep, self.contents)
def makeGroupObject(cls):
def groupAction(s,l,t):
diff --git a/examples/rangeCheck.py b/examples/rangeCheck.py
index 29e9459..66af545 100644
--- a/examples/rangeCheck.py
+++ b/examples/rangeCheck.py
@@ -26,7 +26,7 @@ def ranged_value(expr, minval=None, maxval=None):
outOfRangeMessage = {
(True, False) : "value is greater than %s" % maxval,
(False, True) : "value is less than %s" % minval,
- (False, False) : "value is not in the range ({0} to {1})".format(minval,maxval),
+ (False, False) : "value is not in the range ({} to {})".format(minval,maxval),
}[minval is None, maxval is None]
return expr().addCondition(inRangeCondition, message=outOfRangeMessage)
diff --git a/examples/romanNumerals.py b/examples/romanNumerals.py
index 6e675a9..757a925 100644
--- a/examples/romanNumerals.py
+++ b/examples/romanNumerals.py
@@ -60,13 +60,13 @@ roman_int_map = {}
for expected, (t, s, e) in enumerate(romanNumeral.scanString(tests), start=1):
orig = tests[s:e]
if t[0] != expected:
- print("{0} {1} {2}".format("==>", t, orig))
+ print("{} {} {}".format("==>", t, orig))
roman_int_map[orig] = t[0]
def verify_value(s, tokens):
expected = roman_int_map[s]
if tokens[0] != expected:
- raise Exception("incorrect value for {0} ({1}), expected {2}".format(s, tokens[0], expected ))
+ raise Exception("incorrect value for {} ({}), expected {}".format(s, tokens[0], expected ))
romanNumeral.runTests("""\
XVI
diff --git a/examples/searchparser.py b/examples/searchparser.py
index 1744448..30231b0 100644
--- a/examples/searchparser.py
+++ b/examples/searchparser.py
@@ -103,7 +103,7 @@ class SearchQueryParser:
).setResultsName("quotes") | operatorWord
operatorParenthesis = Group(
- (Suppress("(") + operatorOr + Suppress(")"))
+ Suppress("(") + operatorOr + Suppress(")")
).setResultsName("parenthesis") | operatorQuotes
operatorNot = Forward()
diff --git a/examples/sexpParser.py b/examples/sexpParser.py
index f678d9a..5c4f14d 100644
--- a/examples/sexpParser.py
+++ b/examples/sexpParser.py
@@ -52,7 +52,7 @@ def verify_length(s, l, t):
if t.len is not None:
t1len = len(t[1])
if t1len != t.len:
- raise pp.ParseFatalException(s, l, "invalid data of length {0}, expected {1}".format(t1len, t.len))
+ raise pp.ParseFatalException(s, l, "invalid data of length {}, expected {}".format(t1len, t.len))
return t[1]
diff --git a/examples/shapes.py b/examples/shapes.py
index 55af19a..b0fe979 100644
--- a/examples/shapes.py
+++ b/examples/shapes.py
@@ -7,7 +7,7 @@
#
# define class hierarchy of Shape classes, with polymorphic area method
-class Shape(object):
+class Shape:
def __init__(self, tokens):
self.__dict__.update(tokens.asDict())
@@ -15,7 +15,7 @@ class Shape(object):
raise NotImplemented()
def __str__(self):
- return "<{0}>: {1}".format(self.__class__.__name__, vars(self))
+ return "<{}>: {}".format(self.__class__.__name__, vars(self))
class Square(Shape):
def area(self):
diff --git a/examples/simpleBool.py b/examples/simpleBool.py
index 28490a2..81f5049 100644
--- a/examples/simpleBool.py
+++ b/examples/simpleBool.py
@@ -16,7 +16,7 @@ from pyparsing import infixNotation, opAssoc, Keyword, Word, alphas
# define classes to be built at parse time, as each matching
# expression type is parsed
-class BoolOperand(object):
+class BoolOperand:
def __init__(self,t):
self.label = t[0]
self.value = eval(t[0])
@@ -27,7 +27,7 @@ class BoolOperand(object):
__repr__ = __str__
-class BoolBinOp(object):
+class BoolBinOp:
def __init__(self,t):
self.args = t[0][0::2]
def __str__(self):
@@ -46,7 +46,7 @@ class BoolOr(BoolBinOp):
reprsymbol = '|'
evalop = any
-class BoolNot(object):
+class BoolNot:
def __init__(self,t):
self.arg = t[0][1]
def __bool__(self):
diff --git a/examples/simpleWiki.py b/examples/simpleWiki.py
index 35346bc..ca660c5 100644
--- a/examples/simpleWiki.py
+++ b/examples/simpleWiki.py
@@ -21,7 +21,7 @@ def convertToHTML_A(s,l,t):
text,url=t[0].split("->")
except ValueError:
raise ParseFatalException(s,l,"invalid URL link reference: " + t[0])
- return '<A href="{0}">{1}</A>'.format(url, text)
+ return '<A href="{}">{}</A>'.format(url, text)
urlRef = QuotedString("{{",endQuoteChar="}}").setParseAction(convertToHTML_A)
diff --git a/examples/sparser.py b/examples/sparser.py
index d4604da..39758d6 100644
--- a/examples/sparser.py
+++ b/examples/sparser.py
@@ -77,12 +77,12 @@ def msg(txt):
def debug(ftn, txt):
"""Used for debugging."""
if debug_p:
- sys.stdout.write("{0}.{1}:{2}\n".format(modname, ftn, txt))
+ sys.stdout.write("{}.{}:{}\n".format(modname, ftn, txt))
sys.stdout.flush()
def fatal(ftn, txt):
"""If can't continue."""
- msg = "{0}.{1}:FATAL:{2}\n".format(modname, ftn, txt)
+ msg = "{}.{}:FATAL:{}\n".format(modname, ftn, txt)
raise SystemExit(msg)
def usage():
@@ -138,18 +138,18 @@ class ParseFileLineByLine:
definition file is available __init__ will then create some pyparsing
helper variables. """
if mode not in ['r', 'w', 'a']:
- raise IOError(0, 'Illegal mode: ' + repr(mode))
+ raise OSError(0, 'Illegal mode: ' + repr(mode))
if string.find(filename, ':/') > 1: # URL
if mode == 'w':
- raise IOError("can't write to a URL")
+ raise OSError("can't write to a URL")
import urllib.request, urllib.parse, urllib.error
self.file = urllib.request.urlopen(filename)
else:
filename = os.path.expanduser(filename)
if mode == 'r' or mode == 'a':
if not os.path.exists(filename):
- raise IOError(2, 'No such file or directory: ' + filename)
+ raise OSError(2, 'No such file or directory: ' + filename)
filen, file_extension = os.path.splitext(filename)
command_dict = {
('.Z', 'r'):
diff --git a/examples/statemachine/libraryBookDemo.py b/examples/statemachine/libraryBookDemo.py
index a5e018d..98f0b2b 100644
--- a/examples/statemachine/libraryBookDemo.py
+++ b/examples/statemachine/libraryBookDemo.py
@@ -15,7 +15,7 @@ class Book(librarybookstate.BookStateMixin):
class RestrictedBook(Book):
def __init__(self):
- super(RestrictedBook, self).__init__()
+ super().__init__()
self._authorized_users = []
def authorize(self, name):
@@ -26,7 +26,7 @@ class RestrictedBook(Book):
if user in self._authorized_users:
super().checkout()
else:
- raise Exception("{0} could not check out restricted book".format(user if user is not None else "anonymous"))
+ raise Exception("{} could not check out restricted book".format(user if user is not None else "anonymous"))
def run_demo():
diff --git a/examples/statemachine/statemachine.py b/examples/statemachine/statemachine.py
index f318ee5..4c8ee1d 100644
--- a/examples/statemachine/statemachine.py
+++ b/examples/statemachine/statemachine.py
@@ -72,10 +72,10 @@ def expand_state_definition(source, loc, tokens):
])
# define all state classes
- statedef.extend("class {0}({1}): pass".format(s, baseStateClass) for s in states)
+ statedef.extend("class {}({}): pass".format(s, baseStateClass) for s in states)
# define state->state transitions
- statedef.extend("{0}._next_state_class = {1}".format(s, fromTo[s]) for s in states if s in fromTo)
+ statedef.extend("{}._next_state_class = {}".format(s, fromTo[s]) for s in states if s in fromTo)
statedef.extend([
"class {baseStateClass}Mixin:".format(baseStateClass=baseStateClass),
@@ -178,20 +178,20 @@ def expand_named_state_definition(source, loc, tokens):
for tn in transitions)
# define all state classes
- statedef.extend("class %s(%s): pass" % (s, baseStateClass)
+ statedef.extend("class {}({}): pass".format(s, baseStateClass)
for s in states)
# 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.extend("%s.%s = classmethod(lambda cls: %s())" % (s, tn_, to_)
+ statedef.extend("{}.{} = classmethod(lambda cls: {}())".format(s, tn_, to_)
for tn_, to_ in trns)
statedef.extend([
"{baseStateClass}.transitions = classmethod(lambda cls: [{transition_class_list}])".format(
baseStateClass=baseStateClass,
- transition_class_list = ', '.join("cls.{0}".format(tn) for tn in transitions)
+ transition_class_list = ', '.join("cls.{}".format(tn) for tn in transitions)
),
"{baseStateClass}.transition_names = [tn.__name__ for tn in {baseStateClass}.transitions()]".format(
baseStateClass=baseStateClass
@@ -236,7 +236,7 @@ namedStateMachine.setParseAction(expand_named_state_definition)
# ======================================================================
# NEW STUFF - Matt Anderson, 2009-11-26
# ======================================================================
-class SuffixImporter(object):
+class SuffixImporter:
"""An importer designed using the mechanism defined in :pep:`302`. I read
the PEP, and also used Doug Hellmann's PyMOTW article `Modules and
Imports`_, as a pattern.
@@ -279,7 +279,7 @@ class SuffixImporter(object):
# it probably isn't even a filesystem path
finder = sys.path_importer_cache.get(dirpath)
if isinstance(finder, (type(None), importlib.machinery.FileFinder)):
- checkpath = os.path.join(dirpath, '{0}.{1}'.format(fullname, self.suffix))
+ checkpath = os.path.join(dirpath, '{}.{}'.format(fullname, self.suffix))
yield checkpath
def find_module(self, fullname, path=None):
@@ -337,4 +337,4 @@ class PystateImporter(SuffixImporter):
PystateImporter.register()
if DEBUG:
- print("registered {0!r} importer".format(PystateImporter.suffix))
+ print("registered {!r} importer".format(PystateImporter.suffix))
diff --git a/examples/statemachine/trafficLightDemo.py b/examples/statemachine/trafficLightDemo.py
index a8fac8c..5ff94b1 100644
--- a/examples/statemachine/trafficLightDemo.py
+++ b/examples/statemachine/trafficLightDemo.py
@@ -18,7 +18,7 @@ class TrafficLight(trafficlightstate.TrafficLightStateMixin):
light = TrafficLight()
for i in range(10):
- print("{0} {1}".format(light, ("STOP", "GO")[light.cars_can_go]))
+ print("{} {}".format(light, ("STOP", "GO")[light.cars_can_go]))
light.crossing_signal()
light.delay()
print()
diff --git a/examples/statemachine/vending_machine.py b/examples/statemachine/vending_machine.py
index f48d2f9..d218608 100644
--- a/examples/statemachine/vending_machine.py
+++ b/examples/statemachine/vending_machine.py
@@ -46,7 +46,7 @@ class VendingMachine(VendingMachineStateMixin):
def press_alpha_button(self):
try:
- super(VendingMachine, self).press_alpha_button()
+ super().press_alpha_button()
except VendingMachineState.InvalidTransitionException as ite:
print(ite)
else:
@@ -54,7 +54,7 @@ class VendingMachine(VendingMachineStateMixin):
def press_digit_button(self):
try:
- super(VendingMachine, self).press_digit_button()
+ super().press_digit_button()
except VendingMachineState.InvalidTransitionException as ite:
print(ite)
else:
@@ -63,7 +63,7 @@ class VendingMachine(VendingMachineStateMixin):
def dispense(self):
try:
- super(VendingMachine, self).dispense()
+ super().dispense()
except VendingMachineState.InvalidTransitionException as ite:
print(ite)
else:
diff --git a/examples/verilogParse.py b/examples/verilogParse.py
index f39883f..2d060e6 100644
--- a/examples/verilogParse.py
+++ b/examples/verilogParse.py
@@ -540,7 +540,7 @@ def Verilog_BNF():
"""
portRef = subscrIdentifier
portExpr = portRef | Group( LBRACE + delimitedList( portRef ) + RBRACE )
- port = portExpr | Group( ( DOT + identifier + LPAR + portExpr + RPAR ) )
+ port = portExpr | Group( DOT + identifier + LPAR + portExpr + RPAR )
moduleHdr = Group ( oneOf("module macromodule") + identifier +
Optional( LPAR + Group( Optional( delimitedList(