Skip to content

Commit

Permalink
Merge branch 'release/2.4.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
fgmacedo committed Nov 5, 2024
2 parents 0610c9d + 90b78fc commit 9434716
Show file tree
Hide file tree
Showing 38 changed files with 1,631 additions and 346 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ jobs:
- name: Install dependencies
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
run: poetry install --no-interaction --no-root --all-extras
- name: Install old pydot for 3.7 only
if: matrix.python-version == 3.7
run: |
source .venv/bin/activate
pip install pydot==2.0.0
#----------------------------------------------
# run ruff
#----------------------------------------------
Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,25 +377,25 @@ There's a lot more to cover, please take a look at our docs:
https://python-statemachine.readthedocs.io.


## Contributing to the project
## Contributing

* <a class="github-button" href="https://github.com/fgmacedo/python-statemachine" data-icon="octicon-star" aria-label="Star fgmacedo/python-statemachine on GitHub">Star this project</a>
* <a class="github-button" href="https://github.com/fgmacedo/python-statemachine/issues" data-icon="octicon-issue-opened" aria-label="Issue fgmacedo/python-statemachine on GitHub">Open an Issue</a>
* <a class="github-button" href="https://github.com/fgmacedo/python-statemachine/fork" data-icon="octicon-repo-forked" aria-label="Fork fgmacedo/python-statemachine on GitHub">Fork</a>

- If you found this project helpful, please consider giving it a star on GitHub.

- **Contribute code**: If you would like to contribute code to this project, please submit a pull
- **Contribute code**: If you would like to contribute code, please submit a pull
request. For more information on how to contribute, please see our [contributing.md](contributing.md) file.

- **Report bugs**: If you find any bugs in this project, please report them by opening an issue
- **Report bugs**: If you find any bugs, please report them by opening an issue
on our GitHub issue tracker.

- **Suggest features**: If you have a great idea for a new feature, please let us know by opening
an issue on our GitHub issue tracker.
- **Suggest features**: If you have an idea for a new feature, of feels something being harder than it should be,
please let us know by opening an issue on our GitHub issue tracker.

- **Documentation**: Help improve this project's documentation by submitting pull requests.
- **Documentation**: Help improve documentation by submitting pull requests.

- **Promote the project**: Help spread the word about this project by sharing it on social media,
- **Promote the project**: Help spread the word by sharing on social media,
writing a blog post, or giving a talk about it. Tag me on Twitter
[@fgmacedo](https://twitter.com/fgmacedo) so I can share it too!
6 changes: 1 addition & 5 deletions docs/actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,6 @@ Use the `enter` or `exit` params available on the `State` constructor.

```{hint}
It's also possible to use an event name as action.
**Be careful to not introduce recursion errors** that will raise `RecursionError` exception.
```

### Bind state actions using decorator syntax
Expand All @@ -162,7 +160,7 @@ It's also possible to use an event name as action.

## Transition actions

For each {ref}`event`, you can register `before`, `on`, and `after` callbacks.
For each {ref}`events`, you can register `before`, `on`, and `after` callbacks.

### Declare transition actions by naming convention

Expand Down Expand Up @@ -221,8 +219,6 @@ using the patterns:

```{hint}
It's also possible to use an event name as action to chain transitions.
**Be careful to not introduce recursion errors**, like `loop = initial.to.itself(after="loop")`, that will raise `RecursionError` exception.
```

### Bind transition actions using decorator syntax
Expand Down
7 changes: 7 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@
:members:
```

## Event

```{eval-rst}
.. autoclass:: statemachine.event.Event
:members: id, name, __call__
```

## EventData

```{eval-rst}
Expand Down
4 changes: 2 additions & 2 deletions docs/async.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
Support for async code was added!
```

The {ref}`StateMachine` fully supports asynchronous code. You can write async {ref}`actions`, {ref}`guards`, and {ref}`event` triggers, while maintaining the same external API for both synchronous and asynchronous codebases.
The {ref}`StateMachine` fully supports asynchronous code. You can write async {ref}`actions`, {ref}`guards`, and {ref}`events` triggers, while maintaining the same external API for both synchronous and asynchronous codebases.

This is achieved through a new concept called "engine," an internal strategy pattern abstraction that manages transitions and callbacks.
This is achieved through a new concept called **engine**, an internal strategy pattern abstraction that manages transitions and callbacks.

There are two engines, {ref}`SyncEngine` and {ref}`AsyncEngine`.

Expand Down
76 changes: 71 additions & 5 deletions docs/guards.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,84 @@ A condition is generally a boolean function, property, or attribute, and must no

There are two variations of Guard clauses available:


cond
: A list of conditions, acting like predicates. A transition is only allowed to occur if
: A list of condition expressions, acting like predicates. A transition is only allowed to occur if
all conditions evaluate to ``True``.
* Single condition: `cond="condition"`
* Multiple conditions: `cond=["condition1", "condition2"]`
* Single condition expression: `cond="condition"` / `cond="<condition expression>"`
* Multiple condition expressions: `cond=["condition1", "condition2"]`

unless
: Same as `cond`, but the transition is only allowed if all conditions evaluate to ``False``.
* Single condition: `unless="condition"`
* Single condition: `unless="condition"` / `unless="<condition expression>"`
* Multiple conditions: `unless=["condition1", "condition2"]`

### Condition expressions

This library supports a mini-language for boolean expressions in conditions, allowing the definition of guards that control transitions based on specified criteria. It includes basic [boolean algebra](https://en.wikipedia.org/wiki/Boolean_algebra) operators, parentheses for controlling precedence, and **names** that refer to attributes on the state machine, its associated model, or registered {ref}`Listeners`.

```{tip}
All condition expressions are evaluated when the State Machine is instantiated. This is by design to help you catch any invalid definitions early, rather than when your state machine is running.
```

The mini-language is based on Python's built-in language and the [`ast`](https://docs.python.org/3/library/ast.html) parser, so there are no surprises if you’re familiar with Python. Below is a formal specification to clarify the structure.

#### Syntax elements

1. **Names**:
- Names refer to attributes on the state machine instance, its model or listeners, used directly in expressions to evaluate conditions.
- Names must consist of alphanumeric characters and underscores (`_`) and cannot begin with a digit (e.g., `is_active`, `count`, `has_permission`).
- Any property name used in the expression must exist as an attribute on the state machine, model instance, or listeners, otherwise, an `InvalidDefinition` error is raised.
- Names can be pointed to `properties`, `attributes` or `methods`. If pointed to `attributes`, the library will create a
wrapper get method so each time the expression is evaluated the current value will be retrieved.

2. **Boolean operators and precedence**:
- The following Boolean operators are supported, listed from highest to lowest precedence:
1. `not` / `!` — Logical negation
2. `and` / `^` — Logical conjunction
3. `or` / `v` — Logical disjunction
- These operators are case-sensitive (e.g., `NOT` and `Not` are not equivalent to `not` and will raise syntax errors).
- Both formats can be used interchangeably, so `!sauron_alive` and `not sauron_alive` are equivalent.

3. **Parentheses for precedence**:
- When operators with the same precedence appear in the expression, evaluation proceeds from left to right, unless parentheses specify a different order.
- Parentheses `(` and `)` are supported to control the order of evaluation in expressions.
- Expressions within parentheses are evaluated first, allowing explicit precedence control (e.g., `(is_admin or is_moderator) and has_permission`).

#### Expression Examples

Examples of valid boolean expressions include:
- `is_logged_in and has_permission`
- `not is_active or is_admin`
- `!(is_guest ^ has_access)`
- `(is_admin or is_moderator) and !is_banned`
- `has_account and (verified or trusted)`
- `frodo_has_ring and gandalf_present or !sauron_alive`

Being used on a transition definition:

```python
start.to(end, cond="frodo_has_ring and gandalf_present or !sauron_alive")
```

#### Summary of grammar rules

The mini-language is formally specified as follows:

```
Name: [A-Za-z_][A-Za-z0-9_]*
Boolean Expression:
<boolean_expr> ::= <term> | <boolean_expr> 'or' <term> | <boolean_expr> 'v' <term>
<term> ::= <factor> | <term> 'and' <factor> | <term> '^' <factor>
<factor> ::= 'not' <factor> | '!' <factor> | '(' <boolean_expr> ')' | <name>
```

```{seealso}
See {ref}`sphx_glr_auto_examples_lor_machine.py` for an example of
using boolean algebra in conditions.
```

```{seealso}
See {ref}`sphx_glr_auto_examples_air_conditioner_machine.py` for an example of
combining multiple transitions to the same event.
Expand Down
8 changes: 7 additions & 1 deletion docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@

## Latest release

To install Python State Machine using [poetry](https://python-poetry.org/):
To install using [uv](https://docs.astral.sh/uv):

```shell
uv add python-statemachine
```

To install using [poetry](https://python-poetry.org/):

```shell
poetry add python-statemachine
Expand Down
89 changes: 89 additions & 0 deletions docs/releases/2.4.0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# StateMachine 2.4.0

*November 5, 2024*

## What's new in 2.4.0

This release introduces powerful new features for the `StateMachine` library: {ref}`Condition expressions` and explicit definition of {ref}`Events`. These updates make it easier to define complex transition conditions and enhance performance, especially in workflows with nested or recursive event structures.

### Python compatibility in 2.4.0

StateMachine 2.4.0 supports Python 3.7, 3.8, 3.9, 3.10, 3.11, 3.12, and 3.13.

### Conditions expressions in 2.4.0

This release introduces support for conditionals with Boolean algebra. You can now use expressions like `or`, `and`, and `not` directly within transition conditions, simplifying the definition of complex state transitions. This allows for more flexible and readable condition setups in your state machine configurations.

Example (with a spoiler of the next highlight):

```py
>>> from statemachine import StateMachine, State, Event

>>> class AnyConditionSM(StateMachine):
... start = State(initial=True)
... end = State(final=True)
...
... submit = Event(
... start.to(end, cond="used_money or used_credit"),
... name="finish order",
... )
...
... used_money: bool = False
... used_credit: bool = False

>>> sm = AnyConditionSM()
>>> sm.submit()
Traceback (most recent call last):
TransitionNotAllowed: Can't finish order when in Start.

>>> sm.used_credit = True
>>> sm.submit()
>>> sm.current_state.id
'end'

```

```{seealso}
See {ref}`Condition expressions` for more details or take a look at the {ref}`sphx_glr_auto_examples_lor_machine.py` example.
```

### Explicit event creation in 2.4.0

Now you can explicit declare {ref}`Events` using the {ref}`event` class. This allows custom naming, translations, and also helps your IDE to know that events are callable.

```py
>>> from statemachine import StateMachine, State, Event

>>> class StartMachine(StateMachine):
... created = State(initial=True)
... started = State(final=True)
...
... start = Event(created.to(started), name="Launch the machine")
...
>>> [e.id for e in StartMachine.events]
['start']
>>> [e.name for e in StartMachine.events]
['Launch the machine']
>>> StartMachine.start.name
'Launch the machine'

```

```{seealso}
See {ref}`Events` for more details.
```

### Recursive state machines (infinite loop)

We removed a note from the docs saying to avoid recursion loops. Since the {ref}`StateMachine 2.0.0` release we've turned the RTC model enabled by default, allowing nested events to occour as all events are put on an internal queue before being executed.

```{seealso}
See {ref}`sphx_glr_auto_examples_recursive_event_machine.py` for an example of an infinite loop state machine declaration using `after` action callback to call the same event over and over again.
```


## Bugfixes in 2.4.0

- Fixes [#484](https://github.com/fgmacedo/python-statemachine/issues/484) issue where nested events inside loops could leak memory by incorrectly
referencing previous `event_data` when queuing the next event. This fix improves performance and stability in event-heavy workflows.
1 change: 1 addition & 0 deletions docs/releases/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Below are release notes through StateMachine and its patch releases.
```{toctree}
:maxdepth: 2
2.4.0
2.3.6
2.3.5
2.3.4
Expand Down
Loading

0 comments on commit 9434716

Please sign in to comment.