Skip to content

Commit b008e6e

Browse files
committed
[decorators] finally-style decorators and idioms
1 parent 0d5b39f commit b008e6e

16 files changed

+426
-3
lines changed

.vscode/settings.json

+5
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,15 @@
1212
"behaviours",
1313
"bierner",
1414
"bungcip",
15+
"epilog",
16+
"graphviz",
17+
"literalinclude",
18+
"noodly",
1519
"omnilib",
1620
"py_trees",
1721
"pydot",
1822
"pypi",
23+
"seealso",
1924
"ufmt",
2025
"usort"
2126
]

CHANGELOG.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Release Notes
33

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

88
2.2.3 (2023-02-08)
99
------------------

docs/demos.rst

+16
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,22 @@ py-trees-demo-eternal-guard
147147
:linenos:
148148
:caption: py_trees/demos/eternal_guard.py
149149

150+
.. _py-trees-demo-eventually-program:
151+
152+
py-trees-demo-eventually
153+
------------------------
154+
155+
.. automodule:: py_trees.demos.eventually
156+
:members:
157+
:special-members:
158+
:show-inheritance:
159+
:synopsis: demo the finally-like decorator
160+
161+
.. literalinclude:: ../py_trees/demos/eventually.py
162+
:language: python
163+
:linenos:
164+
:caption: py_trees/demos/eventually.py
165+
150166
.. _py-trees-demo-logging-program:
151167

152168
py-trees-demo-logging

docs/dot/demo-eventually.dot

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
digraph pastafarianism {
2+
ordering=out;
3+
graph [fontname="times-roman"];
4+
node [fontname="times-roman"];
5+
edge [fontname="times-roman"];
6+
root [fillcolor=orange, fontcolor=black, fontsize=9, label="Ⓜ root", shape=box, style=filled];
7+
SetFlagFalse [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagFalse, shape=ellipse, style=filled];
8+
root -> SetFlagFalse;
9+
Parallel [fillcolor=gold, fontcolor=black, fontsize=9, label="Parallel\nSuccessOnOne", shape=parallelogram, style=filled];
10+
root -> Parallel;
11+
Counter [fillcolor=gray, fontcolor=black, fontsize=9, label=Counter, shape=ellipse, style=filled];
12+
Parallel -> Counter;
13+
Eventually [fillcolor=ghostwhite, fontcolor=black, fontsize=9, label=Eventually, shape=ellipse, style=filled];
14+
Parallel -> Eventually;
15+
SetFlagTrue [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagTrue, shape=ellipse, style=filled];
16+
Eventually -> SetFlagTrue;
17+
}

docs/dot/demo-finally-single-tick.dot

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
digraph pastafarianism {
2+
ordering=out;
3+
graph [fontname="times-roman"];
4+
node [fontname="times-roman"];
5+
edge [fontname="times-roman"];
6+
root [fillcolor=orange, fontcolor=black, fontsize=9, label="Ⓜ root", shape=box, style=filled];
7+
SetFlagFalse [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagFalse, shape=ellipse, style=filled];
8+
root -> SetFlagFalse;
9+
Parallel [fillcolor=gold, fontcolor=black, fontsize=9, label="Parallel\nSuccessOnOne", shape=parallelogram, style=filled];
10+
root -> Parallel;
11+
Counter [fillcolor=gray, fontcolor=black, fontsize=9, label=Counter, shape=ellipse, style=filled];
12+
Parallel -> Counter;
13+
Finally [fillcolor=ghostwhite, fontcolor=black, fontsize=9, label=Finally, shape=ellipse, style=filled];
14+
Parallel -> Finally;
15+
SetFlagTrue [fillcolor=gray, fontcolor=black, fontsize=9, label=SetFlagTrue, shape=ellipse, style=filled];
16+
Finally -> SetFlagTrue;
17+
}

docs/dot/eventually.dot

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
digraph pastafarianism {
2+
ordering=out;
3+
graph [fontname="times-roman"];
4+
node [fontname="times-roman"];
5+
edge [fontname="times-roman"];
6+
Parallel [fillcolor=gold, fontcolor=black, fontsize=9, label="Parallel\nSuccessOnOne", shape=parallelogram, style=filled];
7+
Worker [fillcolor=orange, fontcolor=black, fontsize=9, label="Ⓜ Worker", shape=box, style=filled];
8+
Parallel -> Worker;
9+
Glory [fillcolor=gray, fontcolor=black, fontsize=9, label=Glory, shape=ellipse, style=filled];
10+
Worker -> Glory;
11+
Infamy [fillcolor=gray, fontcolor=black, fontsize=9, label=Infamy, shape=ellipse, style=filled];
12+
Worker -> Infamy;
13+
Eventually [fillcolor=ghostwhite, fontcolor=black, fontsize=9, label=Eventually, shape=ellipse, style=filled];
14+
Parallel -> Eventually;
15+
Colander [fillcolor=gray, fontcolor=black, fontsize=9, label=Colander, shape=ellipse, style=filled];
16+
Eventually -> Colander;
17+
}

docs/examples/eventually.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import py_trees
5+
6+
if __name__ == "__main__":
7+
root = py_trees
8+
task_one = py_trees.behaviours.StatusQueue(
9+
name="Glory",
10+
queue=[
11+
py_trees.common.Status.RUNNING,
12+
],
13+
eventually=py_trees.common.Status.SUCCESS,
14+
)
15+
task_two = py_trees.behaviours.Success(name="Infamy")
16+
worker = py_trees.composites.Sequence(
17+
name="Worker", memory=True, children=[task_one, task_two]
18+
)
19+
root = py_trees.idioms.eventually(
20+
name="Parallel",
21+
worker=worker,
22+
eventually=py_trees.behaviours.Success("Colander"),
23+
)
24+
py_trees.display.render_dot_tree(
25+
root, py_trees.common.string_to_visibility_level("all")
26+
)

docs/images/finally_single_tick.png

49.6 KB
Loading

py_trees/behaviour.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ def iterate(self, direct_descendants: bool = False) -> typing.Iterator[Behaviour
344344
yield child
345345
yield self
346346

347-
# TODO: better type refinement of 'viso=itor'
347+
# TODO: better type refinement of 'visitor'
348348
def visit(self, visitor: typing.Any) -> None:
349349
"""
350350
Introspect on this behaviour with a visitor.

py_trees/behaviours.py

+1
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,7 @@ def update(self) -> common.Status:
280280
:data:`~py_trees.common.Status.RUNNING` while not expired, the given completion status otherwise
281281
"""
282282
self.counter += 1
283+
self.feedback_message = f"count: {self.counter}"
283284
if self.counter <= self.duration:
284285
return common.Status.RUNNING
285286
else:

py_trees/decorators.py

+77
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
* :class:`py_trees.decorators.EternalGuard`
3939
* :class:`py_trees.decorators.Inverter`
4040
* :class:`py_trees.decorators.OneShot`
41+
* :class:`py_trees.decorators.OnTerminate`
4142
* :class:`py_trees.decorators.Repeat`
4243
* :class:`py_trees.decorators.Retry`
4344
* :class:`py_trees.decorators.StatusToBlackboard`
@@ -920,3 +921,79 @@ def update(self) -> common.Status:
920921
the behaviour's new status :class:`~py_trees.common.Status`
921922
"""
922923
return self.decorated.status
924+
925+
926+
class OnTerminate(Decorator):
927+
"""
928+
Trigger the child for a single tick on :meth:`terminate`.
929+
930+
Always return :data:`~py_trees.common.Status.RUNNING` and on
931+
on :meth:`terminate`, call the child's
932+
:meth:`~py_trees.behaviour.Behaviour.update` method, once.
933+
934+
This is useful to cleanup, restore a context switch or to
935+
implement a finally-like behaviour.
936+
937+
.. seealso:: :meth:`py_trees.idioms.eventually`
938+
939+
NB: If you need to persist the execution of the 'finally'-like block for more
940+
than a single tick, you'll need to build that explicitly into your tree. There
941+
are various ways of doing so (with and without the blackboard). One pattern
942+
that works:
943+
944+
.. code-block::
945+
946+
[o] Selector
947+
{-} Sequence
948+
--> Work
949+
--> Finally (Triggers on Success)
950+
{-} Sequence
951+
--> Finally (Triggers on Failure)
952+
--> Failure
953+
"""
954+
955+
def __init__(self, name: str, child: behaviour.Behaviour):
956+
"""
957+
Initialise with the standard decorator arguments.
958+
959+
Args:
960+
name: the decorator name
961+
child: the child to be decorated
962+
"""
963+
super(OnTerminate, self).__init__(name=name, child=child)
964+
965+
def tick(self) -> typing.Iterator[behaviour.Behaviour]:
966+
"""
967+
Bypass the child when ticking.
968+
969+
Yields:
970+
a reference to itself
971+
"""
972+
self.logger.debug(f"{self.__class__.__name__}.tick()")
973+
self.status = self.update()
974+
yield self
975+
976+
def update(self):
977+
"""
978+
Return with :data:`~py_trees.common.Status.RUNNING`.
979+
980+
Returns:
981+
the behaviour's new status :class:`~py_trees.common.Status`
982+
"""
983+
return common.Status.RUNNING
984+
985+
def terminate(self, new_status: common.Status) -> None:
986+
"""Tick the child behaviour once."""
987+
self.logger.debug(
988+
"{}.terminate({})".format(
989+
self.__class__.__name__,
990+
"{}->{}".format(self.status, new_status)
991+
if self.status != new_status
992+
else f"{new_status}",
993+
)
994+
)
995+
if new_status == common.Status.INVALID:
996+
self.decorated.tick_once()
997+
# Do not need to stop the child here - this method
998+
# is only called by Decorator.stop() which will handle
999+
# that responsibility immediately after this method returns.

py_trees/demos/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from . import display_modes # usort:skip # noqa: F401
2222
from . import dot_graphs # usort:skip # noqa: F401
2323
from . import either_or # usort:skip # noqa: F401
24+
from . import eventually # usort:skip # noqa: F401
2425
from . import lifecycle # usort:skip # noqa: F401
2526
from . import selector # usort:skip # noqa: F401
2627
from . import sequence # usort:skip # noqa: F401

0 commit comments

Comments
 (0)