Skip to content

Commit

Permalink
[decorators] finally-style decorators and idioms
Browse files Browse the repository at this point in the history
  • Loading branch information
stonier committed Sep 6, 2023
1 parent 0d5b39f commit b008e6e
Show file tree
Hide file tree
Showing 16 changed files with 426 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,15 @@
"behaviours",
"bierner",
"bungcip",
"epilog",
"graphviz",
"literalinclude",
"noodly",
"omnilib",
"py_trees",
"pydot",
"pypi",
"seealso",
"ufmt",
"usort"
]
Expand Down
2 changes: 1 addition & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Release Notes

Forthcoming
-----------
* ...
* [decorators] finally-style decorators and idioms, `#427 <https://github.com/splintered-reality/py_trees/pull/427>`_

2.2.3 (2023-02-08)
------------------
Expand Down
16 changes: 16 additions & 0 deletions docs/demos.rst
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,22 @@ py-trees-demo-eternal-guard
:linenos:
:caption: py_trees/demos/eternal_guard.py

.. _py-trees-demo-eventually-program:

py-trees-demo-eventually
------------------------

.. automodule:: py_trees.demos.eventually
:members:
:special-members:
:show-inheritance:
:synopsis: demo the finally-like decorator

.. literalinclude:: ../py_trees/demos/eventually.py
:language: python
:linenos:
:caption: py_trees/demos/eventually.py

.. _py-trees-demo-logging-program:

py-trees-demo-logging
Expand Down
17 changes: 17 additions & 0 deletions docs/dot/demo-eventually.dot
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
digraph pastafarianism {
ordering=out;
graph [fontname="times-roman"];
node [fontname="times-roman"];
edge [fontname="times-roman"];
root [fillcolor=orange, fontcolor=black, fontsize=9, label="Ⓜ root", shape=box, style=filled];
SetFlagFalse [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagFalse, shape=ellipse, style=filled];
root -> SetFlagFalse;
Parallel [fillcolor=gold, fontcolor=black, fontsize=9, label="Parallel\nSuccessOnOne", shape=parallelogram, style=filled];
root -> Parallel;
Counter [fillcolor=gray, fontcolor=black, fontsize=9, label=Counter, shape=ellipse, style=filled];
Parallel -> Counter;
Eventually [fillcolor=ghostwhite, fontcolor=black, fontsize=9, label=Eventually, shape=ellipse, style=filled];
Parallel -> Eventually;
SetFlagTrue [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagTrue, shape=ellipse, style=filled];
Eventually -> SetFlagTrue;
}
17 changes: 17 additions & 0 deletions docs/dot/demo-finally-single-tick.dot
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
digraph pastafarianism {
ordering=out;
graph [fontname="times-roman"];
node [fontname="times-roman"];
edge [fontname="times-roman"];
root [fillcolor=orange, fontcolor=black, fontsize=9, label="Ⓜ root", shape=box, style=filled];
SetFlagFalse [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagFalse, shape=ellipse, style=filled];
root -> SetFlagFalse;
Parallel [fillcolor=gold, fontcolor=black, fontsize=9, label="Parallel\nSuccessOnOne", shape=parallelogram, style=filled];
root -> Parallel;
Counter [fillcolor=gray, fontcolor=black, fontsize=9, label=Counter, shape=ellipse, style=filled];
Parallel -> Counter;
Finally [fillcolor=ghostwhite, fontcolor=black, fontsize=9, label=Finally, shape=ellipse, style=filled];
Parallel -> Finally;
SetFlagTrue [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagTrue, shape=ellipse, style=filled];
Finally -> SetFlagTrue;
}
17 changes: 17 additions & 0 deletions docs/dot/eventually.dot
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
digraph pastafarianism {
ordering=out;
graph [fontname="times-roman"];
node [fontname="times-roman"];
edge [fontname="times-roman"];
Parallel [fillcolor=gold, fontcolor=black, fontsize=9, label="Parallel\nSuccessOnOne", shape=parallelogram, style=filled];
Worker [fillcolor=orange, fontcolor=black, fontsize=9, label="Ⓜ Worker", shape=box, style=filled];
Parallel -> Worker;
Glory [fillcolor=gray, fontcolor=black, fontsize=9, label=Glory, shape=ellipse, style=filled];
Worker -> Glory;
Infamy [fillcolor=gray, fontcolor=black, fontsize=9, label=Infamy, shape=ellipse, style=filled];
Worker -> Infamy;
Eventually [fillcolor=ghostwhite, fontcolor=black, fontsize=9, label=Eventually, shape=ellipse, style=filled];
Parallel -> Eventually;
Colander [fillcolor=gray, fontcolor=black, fontsize=9, label=Colander, shape=ellipse, style=filled];
Eventually -> Colander;
}
26 changes: 26 additions & 0 deletions docs/examples/eventually.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import py_trees

if __name__ == "__main__":
root = py_trees
task_one = py_trees.behaviours.StatusQueue(
name="Glory",
queue=[
py_trees.common.Status.RUNNING,
],
eventually=py_trees.common.Status.SUCCESS,
)
task_two = py_trees.behaviours.Success(name="Infamy")
worker = py_trees.composites.Sequence(
name="Worker", memory=True, children=[task_one, task_two]
)
root = py_trees.idioms.eventually(
name="Parallel",
worker=worker,
eventually=py_trees.behaviours.Success("Colander"),
)
py_trees.display.render_dot_tree(
root, py_trees.common.string_to_visibility_level("all")
)
Binary file added docs/images/finally_single_tick.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion py_trees/behaviour.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ def iterate(self, direct_descendants: bool = False) -> typing.Iterator[Behaviour
yield child
yield self

# TODO: better type refinement of 'viso=itor'
# TODO: better type refinement of 'visitor'
def visit(self, visitor: typing.Any) -> None:
"""
Introspect on this behaviour with a visitor.
Expand Down
1 change: 1 addition & 0 deletions py_trees/behaviours.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ def update(self) -> common.Status:
:data:`~py_trees.common.Status.RUNNING` while not expired, the given completion status otherwise
"""
self.counter += 1
self.feedback_message = f"count: {self.counter}"
if self.counter <= self.duration:
return common.Status.RUNNING
else:
Expand Down
77 changes: 77 additions & 0 deletions py_trees/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
* :class:`py_trees.decorators.EternalGuard`
* :class:`py_trees.decorators.Inverter`
* :class:`py_trees.decorators.OneShot`
* :class:`py_trees.decorators.OnTerminate`
* :class:`py_trees.decorators.Repeat`
* :class:`py_trees.decorators.Retry`
* :class:`py_trees.decorators.StatusToBlackboard`
Expand Down Expand Up @@ -920,3 +921,79 @@ def update(self) -> common.Status:
the behaviour's new status :class:`~py_trees.common.Status`
"""
return self.decorated.status


class OnTerminate(Decorator):
"""
Trigger the child for a single tick on :meth:`terminate`.
Always return :data:`~py_trees.common.Status.RUNNING` and on
on :meth:`terminate`, call the child's
:meth:`~py_trees.behaviour.Behaviour.update` method, once.
This is useful to cleanup, restore a context switch or to
implement a finally-like behaviour.
.. seealso:: :meth:`py_trees.idioms.eventually`
NB: If you need to persist the execution of the 'finally'-like block for more
than a single tick, you'll need to build that explicitly into your tree. There
are various ways of doing so (with and without the blackboard). One pattern
that works:
.. code-block::
[o] Selector
{-} Sequence
--> Work
--> Finally (Triggers on Success)
{-} Sequence
--> Finally (Triggers on Failure)
--> Failure
"""

def __init__(self, name: str, child: behaviour.Behaviour):
"""
Initialise with the standard decorator arguments.
Args:
name: the decorator name
child: the child to be decorated
"""
super(OnTerminate, self).__init__(name=name, child=child)

def tick(self) -> typing.Iterator[behaviour.Behaviour]:
"""
Bypass the child when ticking.
Yields:
a reference to itself
"""
self.logger.debug(f"{self.__class__.__name__}.tick()")
self.status = self.update()
yield self

def update(self):
"""
Return with :data:`~py_trees.common.Status.RUNNING`.
Returns:
the behaviour's new status :class:`~py_trees.common.Status`
"""
return common.Status.RUNNING

def terminate(self, new_status: common.Status) -> None:
"""Tick the child behaviour once."""
self.logger.debug(
"{}.terminate({})".format(
self.__class__.__name__,
"{}->{}".format(self.status, new_status)
if self.status != new_status
else f"{new_status}",
)
)
if new_status == common.Status.INVALID:
self.decorated.tick_once()
# Do not need to stop the child here - this method
# is only called by Decorator.stop() which will handle
# that responsibility immediately after this method returns.
1 change: 1 addition & 0 deletions py_trees/demos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from . import display_modes # usort:skip # noqa: F401
from . import dot_graphs # usort:skip # noqa: F401
from . import either_or # usort:skip # noqa: F401
from . import eventually # usort:skip # noqa: F401
from . import lifecycle # usort:skip # noqa: F401
from . import selector # usort:skip # noqa: F401
from . import sequence # usort:skip # noqa: F401
Expand Down
Loading

0 comments on commit b008e6e

Please sign in to comment.