python-statemachine 2.2.0__tar.gz → 2.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/PKG-INFO +88 -27
  2. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/README.md +83 -23
  3. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/pyproject.toml +21 -13
  4. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/__init__.py +1 -1
  5. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/callbacks.py +14 -9
  6. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/dispatcher.py +18 -15
  7. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/event.py +21 -20
  8. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/exceptions.py +9 -3
  9. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/factory.py +1 -2
  10. python_statemachine-2.3.1/statemachine/locale/en/LC_MESSAGES/statemachine.po +80 -0
  11. python_statemachine-2.3.1/statemachine/locale/pt_BR/LC_MESSAGES/statemachine.po +91 -0
  12. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/signature.py +13 -5
  13. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/statemachine.py +78 -25
  14. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/transition.py +4 -4
  15. python_statemachine-2.3.1/statemachine/utils.py +39 -0
  16. python_statemachine-2.2.0/statemachine/locale/en/LC_MESSAGES/statemachine.po +0 -66
  17. python_statemachine-2.2.0/statemachine/locale/pt_BR/LC_MESSAGES/statemachine.po +0 -70
  18. python_statemachine-2.2.0/statemachine/utils.py +0 -18
  19. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/LICENSE +0 -0
  20. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/contrib/__init__.py +0 -0
  21. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/contrib/diagram.py +0 -0
  22. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/event_data.py +0 -0
  23. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/events.py +0 -0
  24. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/graph.py +0 -0
  25. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/i18n.py +0 -0
  26. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/mixins.py +0 -0
  27. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/model.py +0 -0
  28. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/registry.py +0 -0
  29. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/state.py +0 -0
  30. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/states.py +0 -0
  31. {python_statemachine-2.2.0 → python_statemachine-2.3.1}/statemachine/transition_list.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-statemachine
3
- Version: 2.2.0
3
+ Version: 2.3.1
4
4
  Summary: Python Finite State Machines made easy.
5
5
  Home-page: https://github.com/fgmacedo/python-statemachine
6
6
  License: MIT
@@ -8,17 +8,18 @@ Author: Fernando Macedo
8
8
  Author-email: fgmacedo@gmail.com
9
9
  Maintainer: Fernando Macedo
10
10
  Maintainer-email: fgmacedo@gmail.com
11
- Requires-Python: >=3.9,<3.13
11
+ Requires-Python: >=3.7
12
+ Classifier: Framework :: AsyncIO
12
13
  Classifier: Intended Audience :: Developers
13
14
  Classifier: License :: OSI Approved :: MIT License
14
15
  Classifier: Natural Language :: English
15
16
  Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Classifier: Programming Language :: Python :: 3.8
16
19
  Classifier: Programming Language :: Python :: 3.9
17
20
  Classifier: Programming Language :: Python :: 3.10
18
21
  Classifier: Programming Language :: Python :: 3.11
19
22
  Classifier: Programming Language :: Python :: 3.12
20
- Classifier: Programming Language :: Python :: 3.7
21
- Classifier: Programming Language :: Python :: 3.8
22
23
  Classifier: Topic :: Software Development :: Libraries
23
24
  Provides-Extra: diagrams
24
25
  Description-Content-Type: text/markdown
@@ -26,8 +27,8 @@ Description-Content-Type: text/markdown
26
27
  # Python StateMachine
27
28
 
28
29
  [![pypi](https://img.shields.io/pypi/v/python-statemachine.svg)](https://pypi.python.org/pypi/python-statemachine)
30
+ [![downloads total](https://static.pepy.tech/badge/python-statemachine)](https://pepy.tech/project/python-statemachine)
29
31
  [![downloads](https://img.shields.io/pypi/dm/python-statemachine.svg)](https://pypi.python.org/pypi/python-statemachine)
30
- [![build status](https://github.com/fgmacedo/python-statemachine/actions/workflows/python-package.yml/badge.svg?branch=develop)](https://github.com/fgmacedo/python-statemachine/actions/workflows/python-package.yml?query=branch%3Adevelop)
31
32
  [![Coverage report](https://codecov.io/gh/fgmacedo/python-statemachine/branch/develop/graph/badge.svg)](https://codecov.io/gh/fgmacedo/python-statemachine)
32
33
  [![Documentation Status](https://readthedocs.org/projects/python-statemachine/badge/?version=latest)](https://python-statemachine.readthedocs.io/en/latest/?badge=latest)
33
34
  [![GitHub commits since last release (main)](https://img.shields.io/github/commits-since/fgmacedo/python-statemachine/main/develop)](https://github.com/fgmacedo/python-statemachine/compare/main...develop)
@@ -35,33 +36,43 @@ Description-Content-Type: text/markdown
35
36
 
36
37
  Python [finite-state machines](https://en.wikipedia.org/wiki/Finite-state_machine) made easy.
37
38
 
39
+ <div align="center">
38
40
 
39
- * Free software: MIT license
40
- * Documentation: https://python-statemachine.readthedocs.io.
41
-
42
-
43
- Welcome to python-statemachine, an intuitive and powerful state machine framework designed for a
44
- great developer experience.
45
-
46
- 🚀 With StateMachine, you can easily create complex, dynamic systems with clean, readable code.
41
+ ![](https://github.com/fgmacedo/python-statemachine/blob/develop/docs/images/python-statemachine.png?raw=true)
47
42
 
48
- 💡 Our framework makes it easy to understand and reason about the different states, events and
49
- transitions in your system, so you can focus on building great products.
43
+ </div>
50
44
 
51
- 🔒 python-statemachine also provides robust error handling and ensures that your system stays
52
- in a valid state at all times.
45
+ Welcome to python-statemachine, an intuitive and powerful state machine library designed for a
46
+ great developer experience. We provide a _pythonic_ and expressive API for implementing state
47
+ machines in sync or asynchonous Python codebases.
53
48
 
49
+ ## Features
54
50
 
55
- A few reasons why you may consider using it:
51
+ - **Basic components**: Easily define **States**, **Events**, and **Transitions** to model your logic.
52
+ - ⚙️ **Actions and handlers**: Attach actions and handlers to states, events, and transitions to control behavior dynamically.
53
+ - 🛡️ **Conditional transitions**: Implement **Guards** and **Validators** to conditionally control transitions, ensuring they only occur when specific conditions are met.
54
+ - 🚀 **Full async support**: Enjoy full asynchronous support. Await events, and dispatch callbacks asynchronously for seamless integration with async codebases.
55
+ - 🔄 **Full sync support**: Use the same state machine from synchronous codebases without any modifications.
56
+ - 🎨 **Declarative and simple API**: Utilize a clean, elegant, and readable API to define your state machine, making it easy to maintain and understand.
57
+ - 👀 **Observer pattern support**: Register external and generic objects to watch events and register callbacks.
58
+ - 🔍 **Decoupled design**: Separate concerns with a decoupled "state machine" and "model" design, promoting cleaner architecture and easier maintenance.
59
+ - ✅ **Correctness guarantees**: Ensured correctness with validations at class definition time:
60
+ - Ensures exactly one `initial` state.
61
+ - Disallows transitions from `final` states.
62
+ - Requires ongoing transitions for all non-final states.
63
+ - Guarantees all non-final states have at least one path to a final state if final states are declared.
64
+ - Validates the state machine graph representation has a single component.
65
+ - 📦 **Flexible event dispatching**: Dispatch events with any extra data, making it available to all callbacks, including actions and guards.
66
+ - 🔧 **Dependency injection**: Needed parameters are injected into callbacks.
67
+ - 📊 **Graphical representation**: Generate and output graphical representations of state machines. Create diagrams from the command line, at runtime, or even in Jupyter notebooks.
68
+ - 🌍 **Internationalization support**: Provides error messages in different languages, making the library accessible to a global audience.
69
+ - 🛡️ **Robust testing**: Ensured reliability with a codebase that is 100% covered by automated tests, including all docs examples. Releases follow semantic versioning for predictable releases.
70
+ - 🏛️ **Domain model integration**: Seamlessly integrate with domain models using Mixins.
71
+ - 🔧 **Django integration**: Automatically discover state machines in Django applications.
56
72
 
57
- * 📈 python-statemachine is designed to help you build scalable,
58
- maintainable systems that can handle any complexity.
59
- * 💪 You can easily create and manage multiple state machines within a single application.
60
- * 🚫 Prevents common mistakes and ensures that your system stays in a valid state at all times.
61
73
 
62
74
 
63
- ## Getting started
64
-
75
+ ## Installing
65
76
 
66
77
  To install Python State Machine, run this command in your terminal:
67
78
 
@@ -73,6 +84,8 @@ our docs for more details.
73
84
 
74
85
  pip install python-statemachine[diagrams]
75
86
 
87
+ ## First example
88
+
76
89
  Define your state machine:
77
90
 
78
91
  ```py
@@ -90,7 +103,7 @@ Define your state machine:
90
103
  ... | red.to(green)
91
104
  ... )
92
105
  ...
93
- ... def before_cycle(self, event: str, source: State, target: State, message: str = ""):
106
+ ... async def before_cycle(self, event: str, source: State, target: State, message: str = ""):
94
107
  ... message = ". " + message if message else ""
95
108
  ... return f"Running {event} from {source.id} to {target.id}{message}"
96
109
  ...
@@ -133,7 +146,27 @@ Then start sending events to your new state machine:
133
146
 
134
147
  ```
135
148
 
136
- That's it. This is all an external object needs to know about your state machine: How to send events.
149
+ You can use the exactly same state machine from an async codebase:
150
+
151
+
152
+ ```py
153
+ >>> async def run_sm():
154
+ ... asm = TrafficLightMachine()
155
+ ... results = []
156
+ ... for _i in range(4):
157
+ ... result = await asm.send("cycle")
158
+ ... results.append(result)
159
+ ... return results
160
+
161
+ >>> asyncio.run(run_sm())
162
+ Don't move.
163
+ Go ahead!
164
+ ['Running cycle from green to yellow', 'Running cycle from yellow to red', ...
165
+
166
+ ```
167
+
168
+
169
+ **That's it.** This is all an external object needs to know about your state machine: How to send events.
137
170
  Ideally, all states, transitions, and actions should be kept internally and not checked externally to avoid unnecessary coupling.
138
171
 
139
172
  But if your use case needs, you can inspect state machine properties, like the current state:
@@ -220,7 +253,7 @@ callback method.
220
253
  Note how `before_cycle` was declared:
221
254
 
222
255
  ```py
223
- def before_cycle(self, event: str, source: State, target: State, message: str = ""):
256
+ async def before_cycle(self, event: str, source: State, target: State, message: str = ""):
224
257
  message = ". " + message if message else ""
225
258
  return f"Running {event} from {source.id} to {target.id}{message}"
226
259
  ```
@@ -265,6 +298,34 @@ and in diagrams:
265
298
 
266
299
  ```
267
300
 
301
+ ## Async support
302
+
303
+ We support native coroutine using `asyncio`, enabling seamless integration with asynchronous code.
304
+ There's no change on the public API of the library to work on async codebases.
305
+
306
+
307
+ ```py
308
+ >>> class AsyncStateMachine(StateMachine):
309
+ ... initial = State('Initial', initial=True)
310
+ ... final = State('Final', final=True)
311
+ ...
312
+ ... advance = initial.to(final)
313
+ ...
314
+ ... async def on_advance(self):
315
+ ... return 42
316
+
317
+ >>> async def run_sm():
318
+ ... sm = AsyncStateMachine()
319
+ ... result = await sm.advance()
320
+ ... print(f"Result is {result}")
321
+ ... print(sm.current_state)
322
+
323
+ >>> asyncio.run(run_sm())
324
+ Result is 42
325
+ Final
326
+
327
+ ```
328
+
268
329
  ## A more useful example
269
330
 
270
331
  A simple didactic state machine for controlling an `Order`:
@@ -1,8 +1,8 @@
1
1
  # Python StateMachine
2
2
 
3
3
  [![pypi](https://img.shields.io/pypi/v/python-statemachine.svg)](https://pypi.python.org/pypi/python-statemachine)
4
+ [![downloads total](https://static.pepy.tech/badge/python-statemachine)](https://pepy.tech/project/python-statemachine)
4
5
  [![downloads](https://img.shields.io/pypi/dm/python-statemachine.svg)](https://pypi.python.org/pypi/python-statemachine)
5
- [![build status](https://github.com/fgmacedo/python-statemachine/actions/workflows/python-package.yml/badge.svg?branch=develop)](https://github.com/fgmacedo/python-statemachine/actions/workflows/python-package.yml?query=branch%3Adevelop)
6
6
  [![Coverage report](https://codecov.io/gh/fgmacedo/python-statemachine/branch/develop/graph/badge.svg)](https://codecov.io/gh/fgmacedo/python-statemachine)
7
7
  [![Documentation Status](https://readthedocs.org/projects/python-statemachine/badge/?version=latest)](https://python-statemachine.readthedocs.io/en/latest/?badge=latest)
8
8
  [![GitHub commits since last release (main)](https://img.shields.io/github/commits-since/fgmacedo/python-statemachine/main/develop)](https://github.com/fgmacedo/python-statemachine/compare/main...develop)
@@ -10,33 +10,43 @@
10
10
 
11
11
  Python [finite-state machines](https://en.wikipedia.org/wiki/Finite-state_machine) made easy.
12
12
 
13
+ <div align="center">
13
14
 
14
- * Free software: MIT license
15
- * Documentation: https://python-statemachine.readthedocs.io.
15
+ ![](https://github.com/fgmacedo/python-statemachine/blob/develop/docs/images/python-statemachine.png?raw=true)
16
16
 
17
+ </div>
17
18
 
18
- Welcome to python-statemachine, an intuitive and powerful state machine framework designed for a
19
- great developer experience.
19
+ Welcome to python-statemachine, an intuitive and powerful state machine library designed for a
20
+ great developer experience. We provide a _pythonic_ and expressive API for implementing state
21
+ machines in sync or asynchonous Python codebases.
20
22
 
21
- 🚀 With StateMachine, you can easily create complex, dynamic systems with clean, readable code.
23
+ ## Features
22
24
 
23
- 💡 Our framework makes it easy to understand and reason about the different states, events and
24
- transitions in your system, so you can focus on building great products.
25
+ - **Basic components**: Easily define **States**, **Events**, and **Transitions** to model your logic.
26
+ - ⚙️ **Actions and handlers**: Attach actions and handlers to states, events, and transitions to control behavior dynamically.
27
+ - 🛡️ **Conditional transitions**: Implement **Guards** and **Validators** to conditionally control transitions, ensuring they only occur when specific conditions are met.
28
+ - 🚀 **Full async support**: Enjoy full asynchronous support. Await events, and dispatch callbacks asynchronously for seamless integration with async codebases.
29
+ - 🔄 **Full sync support**: Use the same state machine from synchronous codebases without any modifications.
30
+ - 🎨 **Declarative and simple API**: Utilize a clean, elegant, and readable API to define your state machine, making it easy to maintain and understand.
31
+ - 👀 **Observer pattern support**: Register external and generic objects to watch events and register callbacks.
32
+ - 🔍 **Decoupled design**: Separate concerns with a decoupled "state machine" and "model" design, promoting cleaner architecture and easier maintenance.
33
+ - ✅ **Correctness guarantees**: Ensured correctness with validations at class definition time:
34
+ - Ensures exactly one `initial` state.
35
+ - Disallows transitions from `final` states.
36
+ - Requires ongoing transitions for all non-final states.
37
+ - Guarantees all non-final states have at least one path to a final state if final states are declared.
38
+ - Validates the state machine graph representation has a single component.
39
+ - 📦 **Flexible event dispatching**: Dispatch events with any extra data, making it available to all callbacks, including actions and guards.
40
+ - 🔧 **Dependency injection**: Needed parameters are injected into callbacks.
41
+ - 📊 **Graphical representation**: Generate and output graphical representations of state machines. Create diagrams from the command line, at runtime, or even in Jupyter notebooks.
42
+ - 🌍 **Internationalization support**: Provides error messages in different languages, making the library accessible to a global audience.
43
+ - 🛡️ **Robust testing**: Ensured reliability with a codebase that is 100% covered by automated tests, including all docs examples. Releases follow semantic versioning for predictable releases.
44
+ - 🏛️ **Domain model integration**: Seamlessly integrate with domain models using Mixins.
45
+ - 🔧 **Django integration**: Automatically discover state machines in Django applications.
25
46
 
26
- 🔒 python-statemachine also provides robust error handling and ensures that your system stays
27
- in a valid state at all times.
28
47
 
29
48
 
30
- A few reasons why you may consider using it:
31
-
32
- * 📈 python-statemachine is designed to help you build scalable,
33
- maintainable systems that can handle any complexity.
34
- * 💪 You can easily create and manage multiple state machines within a single application.
35
- * 🚫 Prevents common mistakes and ensures that your system stays in a valid state at all times.
36
-
37
-
38
- ## Getting started
39
-
49
+ ## Installing
40
50
 
41
51
  To install Python State Machine, run this command in your terminal:
42
52
 
@@ -48,6 +58,8 @@ our docs for more details.
48
58
 
49
59
  pip install python-statemachine[diagrams]
50
60
 
61
+ ## First example
62
+
51
63
  Define your state machine:
52
64
 
53
65
  ```py
@@ -65,7 +77,7 @@ Define your state machine:
65
77
  ... | red.to(green)
66
78
  ... )
67
79
  ...
68
- ... def before_cycle(self, event: str, source: State, target: State, message: str = ""):
80
+ ... async def before_cycle(self, event: str, source: State, target: State, message: str = ""):
69
81
  ... message = ". " + message if message else ""
70
82
  ... return f"Running {event} from {source.id} to {target.id}{message}"
71
83
  ...
@@ -108,7 +120,27 @@ Then start sending events to your new state machine:
108
120
 
109
121
  ```
110
122
 
111
- That's it. This is all an external object needs to know about your state machine: How to send events.
123
+ You can use the exactly same state machine from an async codebase:
124
+
125
+
126
+ ```py
127
+ >>> async def run_sm():
128
+ ... asm = TrafficLightMachine()
129
+ ... results = []
130
+ ... for _i in range(4):
131
+ ... result = await asm.send("cycle")
132
+ ... results.append(result)
133
+ ... return results
134
+
135
+ >>> asyncio.run(run_sm())
136
+ Don't move.
137
+ Go ahead!
138
+ ['Running cycle from green to yellow', 'Running cycle from yellow to red', ...
139
+
140
+ ```
141
+
142
+
143
+ **That's it.** This is all an external object needs to know about your state machine: How to send events.
112
144
  Ideally, all states, transitions, and actions should be kept internally and not checked externally to avoid unnecessary coupling.
113
145
 
114
146
  But if your use case needs, you can inspect state machine properties, like the current state:
@@ -195,7 +227,7 @@ callback method.
195
227
  Note how `before_cycle` was declared:
196
228
 
197
229
  ```py
198
- def before_cycle(self, event: str, source: State, target: State, message: str = ""):
230
+ async def before_cycle(self, event: str, source: State, target: State, message: str = ""):
199
231
  message = ". " + message if message else ""
200
232
  return f"Running {event} from {source.id} to {target.id}{message}"
201
233
  ```
@@ -240,6 +272,34 @@ and in diagrams:
240
272
 
241
273
  ```
242
274
 
275
+ ## Async support
276
+
277
+ We support native coroutine using `asyncio`, enabling seamless integration with asynchronous code.
278
+ There's no change on the public API of the library to work on async codebases.
279
+
280
+
281
+ ```py
282
+ >>> class AsyncStateMachine(StateMachine):
283
+ ... initial = State('Initial', initial=True)
284
+ ... final = State('Final', final=True)
285
+ ...
286
+ ... advance = initial.to(final)
287
+ ...
288
+ ... async def on_advance(self):
289
+ ... return 42
290
+
291
+ >>> async def run_sm():
292
+ ... sm = AsyncStateMachine()
293
+ ... result = await sm.advance()
294
+ ... print(f"Result is {result}")
295
+ ... print(sm.current_state)
296
+
297
+ >>> asyncio.run(run_sm())
298
+ Result is 42
299
+ Final
300
+
301
+ ```
302
+
243
303
  ## A more useful example
244
304
 
245
305
  A simple didactic state machine for controlling an `Order`:
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "python-statemachine"
3
- version = "2.2.0"
3
+ version = "2.3.1"
4
4
  description = "Python Finite State Machines made easy."
5
5
  authors = ["Fernando Macedo <fgmacedo@gmail.com>"]
6
6
  maintainers = [
@@ -27,34 +27,38 @@ classifiers = [
27
27
  "Programming Language :: Python :: 3.10",
28
28
  "Programming Language :: Python :: 3.11",
29
29
  "Programming Language :: Python :: 3.12",
30
- "Topic :: Software Development :: Libraries"
30
+ "Topic :: Software Development :: Libraries",
31
+ "Framework :: AsyncIO",
32
+ "Intended Audience :: Developers",
31
33
  ]
32
34
 
33
35
  [tool.poetry.extras]
34
36
  diagrams = ["pydot"]
35
37
 
36
38
  [tool.poetry.dependencies]
37
- python = ">=3.9, <3.13"
39
+ python = ">=3.7"
38
40
 
39
41
  [tool.poetry.group.dev.dependencies]
40
- pytest = "^8.1.1"
41
- pytest-cov = "^5.0.0"
42
+ pytest = "*"
43
+ pytest-cov = "*"
42
44
  pytest-sugar = "^1.0.0"
43
45
  pydot = "^2.0.0"
44
- ruff = "^0.3.7"
45
- pre-commit = "^3.7.0"
46
- mypy = "^1.9.0"
46
+ ruff = "^0.4.8"
47
+ pre-commit = "*"
48
+ mypy = "*"
47
49
  pytest-mock = "^3.10.0"
48
50
  pytest-profiling = "^1.7.0"
49
51
  pytest-benchmark = "^4.0.0"
52
+ pytest-asyncio = "*"
53
+ sphinx-rtd-theme = "^2.0.0"
50
54
 
51
55
  [tool.poetry.group.docs.dependencies]
52
- Sphinx = "7.2.6"
56
+ Sphinx = "*"
53
57
  sphinx-rtd-theme = "2.0.0"
54
- myst-parser = "^2.0.0"
55
- sphinx-gallery = "^0.15.0"
56
- pillow = "^10.3.0"
57
- sphinx-autobuild = "^2024.4.16"
58
+ myst-parser = "*"
59
+ sphinx-gallery = "*"
60
+ pillow = "*"
61
+ sphinx-autobuild = "*"
58
62
 
59
63
  [build-system]
60
64
  requires = ["poetry-core"]
@@ -63,6 +67,10 @@ build-backend = "poetry.core.masonry.api"
63
67
  [tool.pytest.ini_options]
64
68
  addopts = "--ignore=docs/conf.py --ignore=docs/auto_examples/ --ignore=docs/_build/ --ignore=tests/examples/ --cov --cov-config .coveragerc --doctest-glob='*.md' --doctest-modules --doctest-continue-on-failure --benchmark-autosave"
65
69
  doctest_optionflags = "ELLIPSIS IGNORE_EXCEPTION_DETAIL NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL"
70
+ asyncio_mode = "auto"
71
+ markers = [
72
+ """slow: marks tests as slow (deselect with '-m "not slow"')""",
73
+ ]
66
74
 
67
75
  [tool.mypy]
68
76
  python_version = "3.12"
@@ -3,6 +3,6 @@ from .statemachine import StateMachine
3
3
 
4
4
  __author__ = """Fernando Macedo"""
5
5
  __email__ = "fgmacedo@gmail.com"
6
- __version__ = "2.2.0"
6
+ __version__ = "2.3.1"
7
7
 
8
8
  __all__ = ["StateMachine", "State"]
@@ -20,7 +20,7 @@ class CallbackPriority(IntEnum):
20
20
  AFTER = 40
21
21
 
22
22
 
23
- def allways_true(*args, **kwargs):
23
+ async def allways_true(*args, **kwargs):
24
24
  return True
25
25
 
26
26
 
@@ -46,8 +46,8 @@ class CallbackWrapper:
46
46
  def __lt__(self, other):
47
47
  return self.meta.priority < other.meta.priority
48
48
 
49
- def __call__(self, *args, **kwargs):
50
- return self._callback(*args, **kwargs)
49
+ async def __call__(self, *args, **kwargs):
50
+ return await self._callback(*args, **kwargs)
51
51
 
52
52
 
53
53
  class CallbackMeta:
@@ -137,8 +137,8 @@ class BoolCallbackMeta(CallbackMeta):
137
137
  return name if self.expected_value else f"!{name}"
138
138
 
139
139
  def _wrap_callable(self, func, expected_value):
140
- def bool_wrapper(*args, **kwargs):
141
- return bool(func(*args, **kwargs)) == expected_value
140
+ async def bool_wrapper(*args, **kwargs):
141
+ return bool(await func(*args, **kwargs)) == expected_value
142
142
 
143
143
  return bool_wrapper
144
144
 
@@ -248,13 +248,18 @@ class CallbacksExecutor:
248
248
  self._add(item, resolver)
249
249
  return self
250
250
 
251
- def call(self, *args, **kwargs):
251
+ async def call(self, *args, **kwargs):
252
252
  return [
253
- callback(*args, **kwargs) for callback in self if callback.condition(*args, **kwargs)
253
+ await callback(*args, **kwargs)
254
+ for callback in self
255
+ if await callback.condition(*args, **kwargs)
254
256
  ]
255
257
 
256
- def all(self, *args, **kwargs):
257
- return all(condition(*args, **kwargs) for condition in self)
258
+ async def all(self, *args, **kwargs):
259
+ for condition in self:
260
+ if not await condition(*args, **kwargs):
261
+ return False
262
+ return True
258
263
 
259
264
 
260
265
  class CallbacksRegistry:
@@ -2,6 +2,7 @@ from collections import namedtuple
2
2
  from operator import attrgetter
3
3
  from typing import Any
4
4
  from typing import Generator
5
+ from typing import Tuple
5
6
 
6
7
  from .signature import SignatureAdapter
7
8
 
@@ -15,7 +16,7 @@ class ObjectConfig(namedtuple("ObjectConfig", "obj skip_attrs resolver_id")):
15
16
  """
16
17
 
17
18
  @classmethod
18
- def from_obj(cls, obj, skip_attrs=None):
19
+ def from_obj(cls, obj, skip_attrs=None) -> "ObjectConfig":
19
20
  if isinstance(obj, ObjectConfig):
20
21
  return obj
21
22
  else:
@@ -35,11 +36,11 @@ class WrapSearchResult:
35
36
  def wrap(self): # pragma: no cover
36
37
  pass
37
38
 
38
- def __call__(self, *args: Any, **kwds: Any) -> Any:
39
+ async def __call__(self, *args: Any, **kwds: Any) -> Any:
39
40
  if self._cache is None:
40
41
  self._cache = self.wrap()
41
42
  assert self._cache
42
- return self._cache(*args, **kwds)
43
+ return await self._cache(*args, **kwds)
43
44
 
44
45
 
45
46
  class CallableSearchResult(WrapSearchResult):
@@ -62,7 +63,7 @@ class AttributeCallableSearchResult(WrapSearchResult):
62
63
  # we'll build a method that get's the fresh value for each call
63
64
  getter = attrgetter(self.attribute)
64
65
 
65
- def wrapper(*args, **kwargs):
66
+ async def wrapper(*args, **kwargs):
66
67
  return getter(self.obj)
67
68
 
68
69
  return wrapper
@@ -76,15 +77,15 @@ class EventSearchResult(WrapSearchResult):
76
77
  def wrap(self):
77
78
  "Events already have the 'machine' parameter defined."
78
79
 
79
- def wrapper(*args, **kwargs):
80
+ async def wrapper(*args, **kwargs):
80
81
  kwargs.pop("machine", None)
81
- return self.func(*args, **kwargs)
82
+ return await self.func(*args, **kwargs)
82
83
 
83
84
  return wrapper
84
85
 
85
86
 
86
87
  def _search_callable_attr_is_property(
87
- attr, configs: tuple[ObjectConfig]
88
+ attr, configs: Tuple[ObjectConfig, ...]
88
89
  ) -> "WrapSearchResult | None":
89
90
  # if the attr is a property, we'll try to find the object that has the
90
91
  # property on the configs
@@ -96,7 +97,7 @@ def _search_callable_attr_is_property(
96
97
  return None
97
98
 
98
99
 
99
- def _search_callable_attr_is_callable(attr, configs: tuple[ObjectConfig]) -> WrapSearchResult:
100
+ def _search_callable_attr_is_callable(attr, configs: Tuple[ObjectConfig, ...]) -> WrapSearchResult:
100
101
  # if the attr is an unbounded method, we'll try to find the bounded method
101
102
  # on the configs
102
103
  if not hasattr(attr, "__self__"):
@@ -109,7 +110,7 @@ def _search_callable_attr_is_callable(attr, configs: tuple[ObjectConfig]) -> Wra
109
110
 
110
111
 
111
112
  def _search_callable_in_configs(
112
- attr, configs: tuple[ObjectConfig]
113
+ attr, configs: Tuple[ObjectConfig, ...]
113
114
  ) -> Generator[WrapSearchResult, None, None]:
114
115
  for obj, skip_attrs, resolver_id in configs:
115
116
  if attr in skip_attrs:
@@ -128,7 +129,9 @@ def _search_callable_in_configs(
128
129
  yield CallableSearchResult(attr, func, resolver_id)
129
130
 
130
131
 
131
- def search_callable(attr, configs: tuple) -> Generator[WrapSearchResult, None, None]: # noqa: C901
132
+ def search_callable(
133
+ attr, configs: Tuple[ObjectConfig, ...]
134
+ ) -> Generator[WrapSearchResult, None, None]: # noqa: C901
132
135
  if isinstance(attr, property):
133
136
  result = _search_callable_attr_is_property(attr, configs)
134
137
  if result is not None:
@@ -142,15 +145,15 @@ def search_callable(attr, configs: tuple) -> Generator[WrapSearchResult, None, N
142
145
  yield from _search_callable_in_configs(attr, configs)
143
146
 
144
147
 
145
- def resolver_factory(objects: tuple[ObjectConfig]):
148
+ def resolver_factory(objects: Tuple[ObjectConfig, ...]):
146
149
  """Factory that returns a configured resolver."""
147
150
 
148
- def wrapper(attr) -> Generator[WrapSearchResult, None, None]:
151
+ def resolver(attr) -> Generator[WrapSearchResult, None, None]:
149
152
  yield from search_callable(attr, objects)
150
153
 
151
- return wrapper
154
+ return resolver
152
155
 
153
156
 
154
- def resolver_factory_from_objects(*objects: tuple[Any]):
155
- configs = tuple(ObjectConfig.from_obj(o) for o in objects)
157
+ def resolver_factory_from_objects(*objects: Tuple[Any, ...]):
158
+ configs: Tuple[ObjectConfig, ...] = tuple(ObjectConfig.from_obj(o) for o in objects)
156
159
  return resolver_factory(configs)
@@ -1,5 +1,8 @@
1
+ from functools import partial
1
2
  from typing import TYPE_CHECKING
2
3
 
4
+ from statemachine.utils import run_async_from_sync
5
+
3
6
  from .event_data import EventData
4
7
  from .event_data import TriggerData
5
8
  from .exceptions import TransitionNotAllowed
@@ -15,28 +18,28 @@ class Event:
15
18
  def __repr__(self):
16
19
  return f"{type(self).__name__}({self.name!r})"
17
20
 
18
- def trigger(self, machine: "StateMachine", *args, **kwargs):
19
- def trigger_wrapper():
20
- """Wrapper that captures event_data as closure."""
21
- trigger_data = TriggerData(
22
- machine=machine,
23
- event=self.name,
24
- args=args,
25
- kwargs=kwargs,
26
- )
27
- return self._trigger(trigger_data)
21
+ async def trigger(self, machine: "StateMachine", *args, **kwargs):
22
+ trigger_data = TriggerData(
23
+ machine=machine,
24
+ event=self.name,
25
+ args=args,
26
+ kwargs=kwargs,
27
+ )
28
+ trigger_wrapper = partial(self._trigger, trigger_data=trigger_data)
28
29
 
29
- return machine._process(trigger_wrapper)
30
+ return await machine._process(trigger_wrapper)
30
31
 
31
- def _trigger(self, trigger_data: TriggerData):
32
+ async def _trigger(self, trigger_data: TriggerData):
32
33
  event_data = None
34
+ await trigger_data.machine._ensure_is_initialized()
35
+
33
36
  state = trigger_data.machine.current_state
34
37
  for transition in state.transitions:
35
38
  if not transition.match(trigger_data.event):
36
39
  continue
37
40
 
38
41
  event_data = EventData(trigger_data=trigger_data, transition=transition)
39
- if transition.execute(event_data):
42
+ if await transition.execute(event_data):
40
43
  event_data.executed = True
41
44
  break
42
45
  else:
@@ -46,17 +49,15 @@ class Event:
46
49
  return event_data.result if event_data else None
47
50
 
48
51
 
49
- def trigger_event_factory(event):
52
+ def trigger_event_factory(event_instance: Event):
50
53
  """Build a method that sends specific `event` to the machine"""
51
- event_instance = Event(event)
52
54
 
53
55
  def trigger_event(self, *args, **kwargs):
54
- return event_instance.trigger(self, *args, **kwargs)
55
-
56
- trigger_event.name = event
57
- trigger_event.identifier = event
58
- trigger_event._is_sm_event = True
56
+ return run_async_from_sync(event_instance.trigger(self, *args, **kwargs))
59
57
 
58
+ trigger_event.name = event_instance.name # type: ignore[attr-defined]
59
+ trigger_event.identifier = event_instance.name # type: ignore[attr-defined]
60
+ trigger_event._is_sm_event = True # type: ignore[attr-defined]
60
61
  return trigger_event
61
62
 
62
63