summaryrefslogtreecommitdiff
path: root/examples/statemachine
diff options
context:
space:
mode:
authorJon Dufresne <jon.dufresne@gmail.com>2019-10-31 21:10:28 -0700
committerPaul McGuire <ptmcg@users.noreply.github.com>2019-10-31 23:10:28 -0500
commit53d1b4a6f48a53c4c4ec4ac7031362b691c0366d (patch)
tree088ad3cf3561b78a00af4fb2fd474f4a2b8ca70c /examples/statemachine
parent41752aa52cc97c710474bb2972cceab057b52ad4 (diff)
downloadpyparsing-git-53d1b4a6f48a53c4c4ec4ac7031362b691c0366d.tar.gz
Blacken the project (#141)
Diffstat (limited to 'examples/statemachine')
-rw-r--r--examples/statemachine/documentSignoffDemo.py18
-rw-r--r--examples/statemachine/documentsignoffstate.pystate6
-rw-r--r--examples/statemachine/libraryBookDemo.py16
-rw-r--r--examples/statemachine/statemachine.py287
-rw-r--r--examples/statemachine/vending_machine.py7
-rw-r--r--examples/statemachine/video_demo.py18
6 files changed, 200 insertions, 152 deletions
diff --git a/examples/statemachine/documentSignoffDemo.py b/examples/statemachine/documentSignoffDemo.py
index 2ca38c8..23c902d 100644
--- a/examples/statemachine/documentSignoffDemo.py
+++ b/examples/statemachine/documentSignoffDemo.py
@@ -7,7 +7,12 @@
import statemachine
import documentsignoffstate
-print('\n'.join(t.__name__ for t in documentsignoffstate.DocumentRevisionState.transitions()))
+print(
+ "\n".join(
+ t.__name__ for t in documentsignoffstate.DocumentRevisionState.transitions()
+ )
+)
+
class Document(documentsignoffstate.DocumentRevisionStateMixin):
def __init__(self):
@@ -27,16 +32,16 @@ def run_demo():
while not isinstance(doc._state, documentsignoffstate.Approved):
- print('...submit')
+ print("...submit")
doc.submit()
print(doc)
print(doc.state.description)
- if random.randint(1,10) > 3:
- print('...reject')
+ if random.randint(1, 10) > 3:
+ print("...reject")
doc.reject()
else:
- print('...approve')
+ print("...approve")
doc.approve()
print(doc)
@@ -46,5 +51,6 @@ def run_demo():
print(doc)
print(doc.state.description)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
run_demo()
diff --git a/examples/statemachine/documentsignoffstate.pystate b/examples/statemachine/documentsignoffstate.pystate
index 04df274..0c8fc61 100644
--- a/examples/statemachine/documentsignoffstate.pystate
+++ b/examples/statemachine/documentsignoffstate.pystate
@@ -7,7 +7,7 @@
# example using named state transitions
# This implements a state model for submitting,
-# approving, activating, and purging document
+# approving, activating, and purging document
# revisions in a document management system.
#
# The state model looks like:
@@ -16,7 +16,7 @@
# |
# | (create)
# |
-# v
+# v
# Editing ----------------------------------------------+
# | ^ |
# | | |
@@ -50,7 +50,7 @@
# just an example of a state machine with named transitions.
#
-
+
statemachine DocumentRevisionState:
New -( create )-> Editing
Editing -( cancel )-> Deleted
diff --git a/examples/statemachine/libraryBookDemo.py b/examples/statemachine/libraryBookDemo.py
index 98f0b2b..61bdd6d 100644
--- a/examples/statemachine/libraryBookDemo.py
+++ b/examples/statemachine/libraryBookDemo.py
@@ -26,7 +26,11 @@ class RestrictedBook(Book):
if user in self._authorized_users:
super().checkout()
else:
- raise Exception("{} 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():
@@ -41,9 +45,9 @@ def run_demo():
print(book)
try:
book.checkout()
- except Exception as e: # statemachine.InvalidTransitionException:
+ except Exception as e: # statemachine.InvalidTransitionException:
print(e)
- print('..cannot check out reserved book')
+ print("..cannot check out reserved book")
book.release()
print(book)
book.checkout()
@@ -58,13 +62,13 @@ def run_demo():
try:
restricted_book.checkout(name)
except Exception as e:
- print('..' + str(e))
+ print(".." + str(e))
else:
- print('checkout to', name)
+ print("checkout to", name)
print(restricted_book)
restricted_book.checkin()
print(restricted_book)
-if __name__ == '__main__':
+if __name__ == "__main__":
run_demo()
diff --git a/examples/statemachine/statemachine.py b/examples/statemachine/statemachine.py
index 4c8ee1d..a5f144e 100644
--- a/examples/statemachine/statemachine.py
+++ b/examples/statemachine/statemachine.py
@@ -18,7 +18,8 @@ import pyparsing as pp
# define basic exception for invalid state transitions - state machine classes will subclass to
# define their own specific exception type
-class InvalidTransitionException(Exception): pass
+class InvalidTransitionException(Exception):
+ pass
ident = pp.Word(pp.alphas + "_", pp.alphanums + "_$")
@@ -28,17 +29,30 @@ ident = pp.Word(pp.alphas + "_", pp.alphanums + "_$")
def no_keywords_allowed(s, l, t):
wd = t[0]
return not keyword.iskeyword(wd)
-ident.addCondition(no_keywords_allowed, message="cannot use a Python keyword for state or transition identifier")
-stateTransition = ident("from_state") + "->" + ident("to_state")
-stateMachine = (pp.Keyword("statemachine") + ident("name") + ":"
- + pp.OneOrMore(pp.Group(stateTransition))("transitions"))
-namedStateTransition = (ident("from_state")
- + "-(" + ident("transition") + ")->"
- + ident("to_state"))
-namedStateMachine = (pp.Keyword("statemachine") + ident("name") + ":"
- + pp.OneOrMore(pp.Group(namedStateTransition))("transitions"))
+ident.addCondition(
+ no_keywords_allowed,
+ message="cannot use a Python keyword for state or transition identifier",
+)
+
+stateTransition = ident("from_state") + "->" + ident("to_state")
+stateMachine = (
+ pp.Keyword("statemachine")
+ + ident("name")
+ + ":"
+ + pp.OneOrMore(pp.Group(stateTransition))("transitions")
+)
+
+namedStateTransition = (
+ ident("from_state") + "-(" + ident("transition") + ")->" + ident("to_state")
+)
+namedStateMachine = (
+ pp.Keyword("statemachine")
+ + ident("name")
+ + ":"
+ + pp.OneOrMore(pp.Group(namedStateTransition))("transitions")
+)
def expand_state_definition(source, loc, tokens):
@@ -58,50 +72,53 @@ def expand_state_definition(source, loc, tokens):
# define base class for state classes
baseStateClass = tokens.name
- statedef.extend([
- "class %s(object):" % baseStateClass,
- " def __str__(self):",
- " return self.__class__.__name__",
-
- " @classmethod",
- " def states(cls):",
- " return list(cls.__subclasses__())",
-
- " def next_state(self):",
- " return self._next_state_class()",
- ])
+ statedef.extend(
+ [
+ "class %s(object):" % baseStateClass,
+ " def __str__(self):",
+ " return self.__class__.__name__",
+ " @classmethod",
+ " def states(cls):",
+ " return list(cls.__subclasses__())",
+ " def next_state(self):",
+ " return self._next_state_class()",
+ ]
+ )
# define all state classes
statedef.extend("class {}({}): pass".format(s, baseStateClass) for s in states)
# define state->state transitions
- 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),
- " def __init__(self):",
- " self._state = None",
-
- " def initialize_state(self, init_state):",
- " if issubclass(init_state, {baseStateClass}):".format(baseStateClass=baseStateClass),
- " init_state = init_state()",
- " self._state = init_state",
-
- " @property",
- " def state(self):",
- " return self._state",
-
- " # get behavior/properties from current state",
- " def __getattr__(self, attrname):",
- " attr = getattr(self._state, attrname)",
- " return attr",
+ statedef.extend(
+ "{}._next_state_class = {}".format(s, fromTo[s]) for s in states if s in fromTo
+ )
- " def __str__(self):",
- " return '{0}: {1}'.format(self.__class__.__name__, self._state)",
- ])
+ statedef.extend(
+ [
+ "class {baseStateClass}Mixin:".format(baseStateClass=baseStateClass),
+ " def __init__(self):",
+ " self._state = None",
+ " def initialize_state(self, init_state):",
+ " if issubclass(init_state, {baseStateClass}):".format(
+ baseStateClass=baseStateClass
+ ),
+ " init_state = init_state()",
+ " self._state = init_state",
+ " @property",
+ " def state(self):",
+ " return self._state",
+ " # get behavior/properties from current state",
+ " def __getattr__(self, attrname):",
+ " attr = getattr(self._state, attrname)",
+ " return attr",
+ " def __str__(self):",
+ " return '{0}: {1}'.format(self.__class__.__name__, self._state)",
+ ]
+ )
return ("\n" + indent).join(statedef) + "\n"
+
stateMachine.setParseAction(expand_state_definition)
@@ -134,102 +151,115 @@ def expand_named_state_definition(source, loc, tokens):
fromTo[s] = {}
# define state transition class
- statedef.extend([
- "class {baseStateClass}Transition:".format(baseStateClass=baseStateClass),
- " def __str__(self):",
- " return self.transitionName",
- ])
statedef.extend(
- "{tn_name} = {baseStateClass}Transition()".format(tn_name=tn,
- baseStateClass=baseStateClass)
- for tn in transitions)
- statedef.extend("{tn_name}.transitionName = '{tn_name}'".format(tn_name=tn)
- for tn in transitions)
+ [
+ "class {baseStateClass}Transition:".format(baseStateClass=baseStateClass),
+ " def __str__(self):",
+ " return self.transitionName",
+ ]
+ )
+ statedef.extend(
+ "{tn_name} = {baseStateClass}Transition()".format(
+ tn_name=tn, baseStateClass=baseStateClass
+ )
+ for tn in transitions
+ )
+ statedef.extend(
+ "{tn_name}.transitionName = '{tn_name}'".format(tn_name=tn)
+ for tn in transitions
+ )
# define base class for state classes
- statedef.extend([
- "class %s(object):" % baseStateClass,
- " from statemachine import InvalidTransitionException as BaseTransitionException",
- " class InvalidTransitionException(BaseTransitionException): pass",
- " def __str__(self):",
- " return self.__class__.__name__",
-
- " @classmethod",
- " def states(cls):",
- " return list(cls.__subclasses__())",
-
- " @classmethod",
- " def next_state(cls, name):",
- " try:",
- " return cls.tnmap[name]()",
- " except KeyError:",
- " raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
-
- " def __bad_tn(name):",
- " def _fn(cls):",
- " raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
- " _fn.__name__ = name",
- " return _fn",
- ])
+ statedef.extend(
+ [
+ "class %s(object):" % baseStateClass,
+ " from statemachine import InvalidTransitionException as BaseTransitionException",
+ " class InvalidTransitionException(BaseTransitionException): pass",
+ " def __str__(self):",
+ " return self.__class__.__name__",
+ " @classmethod",
+ " def states(cls):",
+ " return list(cls.__subclasses__())",
+ " @classmethod",
+ " def next_state(cls, name):",
+ " try:",
+ " return cls.tnmap[name]()",
+ " except KeyError:",
+ " raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
+ " def __bad_tn(name):",
+ " def _fn(cls):",
+ " raise cls.InvalidTransitionException('%s does not support transition %r'% (cls.__name__, name))",
+ " _fn.__name__ = name",
+ " return _fn",
+ ]
+ )
# define default 'invalid transition' methods in base class, valid transitions will be implemented in subclasses
statedef.extend(
" {tn_name} = classmethod(__bad_tn({tn_name!r}))".format(tn_name=tn)
- for tn in transitions)
+ for tn in transitions
+ )
# define all state classes
- statedef.extend("class {}({}): pass".format(s, baseStateClass)
- for s in states)
+ 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("{}.{} = 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.{}".format(tn) for tn in transitions)
- ),
- "{baseStateClass}.transition_names = [tn.__name__ for tn in {baseStateClass}.transitions()]".format(
- baseStateClass=baseStateClass
+ statedef.extend(
+ "{}.{} = classmethod(lambda cls: {}())".format(s, tn_, to_)
+ for tn_, to_ in trns
)
- ])
-
- # define <state>Mixin class for application classes that delegate to the state
- statedef.extend([
- "class {baseStateClass}Mixin:".format(baseStateClass=baseStateClass),
- " def __init__(self):",
- " self._state = None",
-
- " def initialize_state(self, init_state):",
- " if issubclass(init_state, {baseStateClass}):".format(baseStateClass=baseStateClass),
- " init_state = init_state()",
- " self._state = init_state",
- " @property",
- " def state(self):",
- " return self._state",
-
- " # get behavior/properties from current state",
- " def __getattr__(self, attrname):",
- " attr = getattr(self._state, attrname)",
- " return attr",
-
- " def __str__(self):",
- " return '{0}: {1}'.format(self.__class__.__name__, self._state)",
+ statedef.extend(
+ [
+ "{baseStateClass}.transitions = classmethod(lambda cls: [{transition_class_list}])".format(
+ baseStateClass=baseStateClass,
+ transition_class_list=", ".join(
+ "cls.{}".format(tn) for tn in transitions
+ ),
+ ),
+ "{baseStateClass}.transition_names = [tn.__name__ for tn in {baseStateClass}.transitions()]".format(
+ baseStateClass=baseStateClass
+ ),
+ ]
+ )
- ])
+ # define <state>Mixin class for application classes that delegate to the state
+ statedef.extend(
+ [
+ "class {baseStateClass}Mixin:".format(baseStateClass=baseStateClass),
+ " def __init__(self):",
+ " self._state = None",
+ " def initialize_state(self, init_state):",
+ " if issubclass(init_state, {baseStateClass}):".format(
+ baseStateClass=baseStateClass
+ ),
+ " init_state = init_state()",
+ " self._state = init_state",
+ " @property",
+ " def state(self):",
+ " return self._state",
+ " # get behavior/properties from current state",
+ " def __getattr__(self, attrname):",
+ " attr = getattr(self._state, attrname)",
+ " return attr",
+ " def __str__(self):",
+ " return '{0}: {1}'.format(self.__class__.__name__, self._state)",
+ ]
+ )
# define transition methods to be delegated to the _state instance variable
statedef.extend(
- " def {tn_name}(self): self._state = self._state.{tn_name}()".format(tn_name=tn)
+ " def {tn_name}(self): self._state = self._state.{tn_name}()".format(
+ tn_name=tn
+ )
for tn in transitions
)
return ("\n" + indent).join(statedef) + "\n"
+
namedStateMachine.setParseAction(expand_named_state_definition)
@@ -248,15 +278,15 @@ class SuffixImporter:
:meth:`register` on your class to actually install it in the appropriate
places in :mod:`sys`. """
- scheme = 'suffix'
+ scheme = "suffix"
suffix = None
path_entry = None
@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("%s.suffix is not set" % cls.__name__)
+ return "suffix:%s" % cls.suffix
@classmethod
def register(cls):
@@ -279,7 +309,7 @@ class SuffixImporter:
# 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, '{}.{}'.format(fullname, self.suffix))
+ checkpath = os.path.join(dirpath, "{}.{}".format(fullname, self.suffix))
yield checkpath
def find_module(self, fullname, path=None):
@@ -311,25 +341,26 @@ class SuffixImporter:
class PystateImporter(SuffixImporter):
- suffix = 'pystate'
+ suffix = "pystate"
def process_filedata(self, module, data):
# MATT-NOTE: re-worked :func:`get_state_machine`
# convert any statemachine expressions
- stateMachineExpr = (stateMachine | namedStateMachine).ignore(pp.pythonStyleComment)
+ stateMachineExpr = (stateMachine | namedStateMachine).ignore(
+ pp.pythonStyleComment
+ )
generated_code = stateMachineExpr.transformString(data)
- if DEBUG: print(generated_code)
+ if DEBUG:
+ print(generated_code)
# compile code object from generated code
# (strip trailing spaces and tabs, compile doesn't like
# dangling whitespace)
- COMPILE_MODE = 'exec'
+ COMPILE_MODE = "exec"
- codeobj = compile(generated_code.rstrip(" \t"),
- module.__file__,
- COMPILE_MODE)
+ codeobj = compile(generated_code.rstrip(" \t"), module.__file__, COMPILE_MODE)
exec(codeobj, module.__dict__)
diff --git a/examples/statemachine/vending_machine.py b/examples/statemachine/vending_machine.py
index d218608..b5fe524 100644
--- a/examples/statemachine/vending_machine.py
+++ b/examples/statemachine/vending_machine.py
@@ -22,11 +22,14 @@ statemachine VendingMachineState:
"""
# convert state machine text to state classes
-generated = statemachine.namedStateMachine.transformString(vending_machine_state_description)
+generated = statemachine.namedStateMachine.transformString(
+ vending_machine_state_description
+)
# print(generated)
# exec generated code to define state classes and state mixin
exec(generated)
+
class VendingMachine(VendingMachineStateMixin):
def __init__(self):
self.initialize_state(Idle)
@@ -42,7 +45,7 @@ class VendingMachine(VendingMachineStateMixin):
self._pressed = button
self.press_digit_button()
else:
- print('Did not recognize button {!r}'.format(str(button)))
+ print("Did not recognize button {!r}".format(str(button)))
def press_alpha_button(self):
try:
diff --git a/examples/statemachine/video_demo.py b/examples/statemachine/video_demo.py
index fadfb9d..f6dbc8f 100644
--- a/examples/statemachine/video_demo.py
+++ b/examples/statemachine/video_demo.py
@@ -20,25 +20,29 @@ v = Video("Die Hard.mp4")
while True:
print(v.state)
- cmd = input("Command ({})> ".format('/'.join(videostate.VideoState.transition_names))).lower().strip()
+ cmd = (
+ input("Command ({})> ".format("/".join(videostate.VideoState.transition_names)))
+ .lower()
+ .strip()
+ )
if not cmd:
continue
- if cmd in ('?', 'h', 'help'):
- print('enter a transition {!r}'.format(videostate.VideoState.transition_names))
- print(' q - quit')
- print(' ?, h, help - this message')
+ if cmd in ("?", "h", "help"):
+ print("enter a transition {!r}".format(videostate.VideoState.transition_names))
+ print(" q - quit")
+ print(" ?, h, help - this message")
continue
# quitting out
- if cmd.startswith('q'):
+ if cmd.startswith("q"):
break
# get transition function for given command
state_transition_fn = getattr(v, cmd, None)
if state_transition_fn is None:
- print('???')
+ print("???")
continue
# invoke the input transition, handle invalid commands