diff --git a/docs/guards.md b/docs/guards.md index 35455604..5e2565be 100644 --- a/docs/guards.md +++ b/docs/guards.md @@ -197,6 +197,38 @@ and passed by reference (`cond=my_condition`). ``` +Callable instances are also supported, including instances with an async `__call__` +method and instances wrapped in `functools.partial`. They receive dependencies by +parameter name, just like functions. The callable stays bound to its own object; +request `machine` to access the state machine. + +```py +>>> class MinimumAmount: +... def __init__(self, minimum): +... self.minimum = minimum +... +... def __call__(self, amount): +... return amount >= self.minimum + +>>> class Payment(StateChart): +... pending = State(initial=True) +... approved = State(final=True) +... approve = pending.to(approved, cond=MinimumAmount(10)) + +>>> payment = Payment() +>>> payment.send("approve", amount=5) +>>> "pending" in payment.configuration_values +True +>>> payment.send("approve", amount=10) +>>> "approved" in payment.configuration_values +True + +``` + +Reusing a callable instance also shares its state between machines. An async +`__call__` selects the async engine, as an async function does. + + (condition expressions)= ### Condition expressions diff --git a/docs/releases/3.3.0.md b/docs/releases/3.3.0.md index 163556be..c57e8959 100644 --- a/docs/releases/3.3.0.md +++ b/docs/releases/3.3.0.md @@ -28,6 +28,14 @@ its output. See [](../contributing.md#uml-cases-based-on-pssm). [#697](https://github.com/fgmacedo/python-statemachine/pull/697). +### Callable guard objects + +Callable instances now work as guards and callbacks, including async `__call__`, +parameter injection, and `functools.partial`. Callback registration preserves the +original object without adding function metadata. This fixes the construction-time +`AttributeError` reported in [#731](https://github.com/fgmacedo/python-statemachine/issues/731). + + ## Behavior changes to check when upgrading Each item below fixes behavior that did not match the documented contract. Code that relied diff --git a/statemachine/callbacks.py b/statemachine/callbacks.py index b564f217..e346debd 100644 --- a/statemachine/callbacks.py +++ b/statemachine/callbacks.py @@ -94,8 +94,9 @@ def __init__( elif callable(func): self.reference = SpecReference.CALLABLE is_partial = isinstance(func, partial) - self.is_bounded = is_partial or hasattr(func, "__self__") - name = func.func.__name__ if is_partial else func.__name__ + self.is_bounded = not isfunction(func) or hasattr(func, "__self__") + metadata = func.func if is_partial else func + name = getattr(metadata, "__name__", type(metadata).__name__) self.attr_name = name if not self.is_event or self.is_bounded else f"_{name}_" if not self.is_bounded: func.attr_name = self.attr_name # type: ignore[union-attr] diff --git a/statemachine/dispatcher.py b/statemachine/dispatcher.py index 2bf4073c..ec86f0ba 100644 --- a/statemachine/dispatcher.py +++ b/statemachine/dispatcher.py @@ -209,7 +209,9 @@ def signature_adapter(*args: Any, **kwargs: Any) -> Any: # type: ignore[misc] ba = sig_bind_expected(*args, **kwargs) return a_callable(*ba.args, **ba.kwargs) - signature_adapter.__name__ = metadata_to_copy.__name__ + signature_adapter.__name__ = getattr( + metadata_to_copy, "__name__", type(metadata_to_copy).__name__ + ) signature_adapter.__doc__ = metadata_to_copy.__doc__ signature_adapter.is_coroutine = sig.is_coroutine # type: ignore[attr-defined] diff --git a/statemachine/factory.py b/statemachine/factory.py index 606553ff..3ebc3010 100644 --- a/statemachine/factory.py +++ b/statemachine/factory.py @@ -215,7 +215,7 @@ def _update_lookup_names(cls, relocated: dict[Any, str], own_states: list[State] return for visited in iterate_states_and_transitions(own_states): for spec in visited._specs: - if spec.reference is SpecReference.CALLABLE and spec.func in relocated: + if is_unbounded_reference(spec.func) and spec.func in relocated: spec.lookup_name = relocated[spec.func] def _all_specs(cls): diff --git a/statemachine/signature.py b/statemachine/signature.py index 20230f77..e753a868 100644 --- a/statemachine/signature.py +++ b/statemachine/signature.py @@ -5,6 +5,7 @@ from inspect import Parameter from inspect import Signature from inspect import iscoroutinefunction +from inspect import isfunction from itertools import chain from types import MethodType from typing import Any @@ -26,8 +27,10 @@ def _make_key(method): method.__code__.co_varnames, ) ) - else: + elif isfunction(method): return hash((method.__qualname__, method.__code__.co_varnames)) + # Callable instances may be unhashable or expose instance-specific signatures. + return None def signature_cache(user_function): @@ -36,6 +39,8 @@ def signature_cache(user_function): def cached_function(cls, method): key = _make_key(method) + if key is None: + return user_function(cls, method) sig = cache_get(key) if sig is None: sig = user_function(cls, method) @@ -60,16 +65,15 @@ def __init__(self, *args, **kwargs): @classmethod @signature_cache def from_callable(cls, method): - if hasattr(method, "__signature__"): - sig = method.__signature__ - adapter = SignatureAdapter( - sig.parameters.values(), - return_annotation=sig.return_annotation, - ) - else: - adapter = super().from_callable(method) - - adapter.is_coroutine = iscoroutinefunction(method) + sig = super().from_callable(method) + adapter = cls(sig.parameters.values(), return_annotation=sig.return_annotation) + + implementation = method + while isinstance(implementation, partial): + implementation = implementation.func + adapter.is_coroutine = iscoroutinefunction(implementation) or ( + not isfunction(implementation) and iscoroutinefunction(implementation.__call__) + ) return adapter def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: diff --git a/tests/test_callable_instances.py b/tests/test_callable_instances.py new file mode 100644 index 00000000..b2284ae7 --- /dev/null +++ b/tests/test_callable_instances.py @@ -0,0 +1,255 @@ +from functools import partial +from inspect import Parameter +from inspect import Signature + +import pytest +from statemachine.callbacks import CallbackGroup +from statemachine.callbacks import CallbackSpec +from statemachine.dispatcher import callable_method +from statemachine.engines.async_ import AsyncEngine +from statemachine.exceptions import TransitionNotAllowed +from statemachine.signature import SignatureAdapter + +from statemachine import State +from statemachine import StateChart + + +class Guard: + __slots__ = ("calls", "allowed") + + def __init__(self, allowed=True): + self.calls = [] + self.allowed = allowed + + def __call__(self, machine, event, *, amount=0): + self.calls.append((machine, event, amount)) + return self.allowed and amount > 0 + + +@pytest.mark.parametrize("reference", ["direct", "named", "partial"]) +async def test_callable_guard_injects_arguments_and_preserves_instance(sm_runner, reference): + guard = Guard() + callback = partial(guard, amount=7) if reference == "partial" else guard + + class Machine(StateChart): + allow_event_without_transition = False + catch_errors_as_events = False + a = State(initial=True) + b = State(final=True) + condition = callback + go = a.to(b, cond="condition" if reference == "named" else callback) + + machine = await sm_runner.start(Machine) + guard.allowed = False + with pytest.raises(TransitionNotAllowed): + await sm_runner.send(machine, "go", amount=4, ignored="value") + assert "a" in machine.configuration_values + guard.allowed = True + await sm_runner.send(machine, "go", amount=4, ignored="value") + assert "b" in machine.configuration_values + assert guard.calls == [(machine, "go", 4), (machine, "go", 4)] + + +async def test_callable_guards_do_not_share_instance_state(sm_runner): + first = Guard(allowed=False) + second = Guard() + + class Machine(StateChart): + allow_event_without_transition = False + catch_errors_as_events = False + a = State(initial=True) + b = State(final=True) + go = a.to(b, cond=[first, second]) + + machine = await sm_runner.start(Machine) + with pytest.raises(TransitionNotAllowed): + await sm_runner.send(machine, "go", amount=1) + assert len(first.calls) == 1 + assert second.calls == [] + first.allowed = True + await sm_runner.send(machine, "go", amount=2) + assert first.calls[-1] == second.calls[-1] == (machine, "go", 2) + assert "b" in machine.configuration_values + + +@pytest.mark.parametrize("form", ["direct", "partial", "nested_partial"]) +async def test_async_callable_guard_selects_async_engine_and_awaits_result(form): + calls = [] + + class AsyncGuard: + __slots__ = () + + async def __call__(self, machine, *, allowed=False): + calls.append((self, machine, allowed)) + return allowed + + guard = AsyncGuard() + callback = partial(guard, allowed=False) if form != "direct" else guard + if form == "nested_partial": + callback.description = "preserve the nested partial" + callback = partial(callback) + + class Machine(StateChart): + allow_event_without_transition = False + catch_errors_as_events = False + a = State(initial=True) + b = State(final=True) + go = a.to(b, cond=callback) + + machine = Machine() + assert isinstance(machine._engine, AsyncEngine) + await machine.activate_initial_state() + with pytest.raises(TransitionNotAllowed): + await machine.go(allowed=False) + assert "a" in machine.configuration_values + await machine.go(allowed=True) + assert "b" in machine.configuration_values + assert calls == [(guard, machine, False), (guard, machine, True)] + + +def test_callable_signature_does_not_mutate_user_object(): + class Callable: + def __call__(self, value): + return value + + target = Callable() + original_attributes = vars(target).copy() + spec = CallbackSpec(target, group=CallbackGroup.COND) + assert spec.func is target + adapted = callable_method(target) + assert adapted(value=3, ignored=True) == 3 + assert adapted(value=5, ignored=False) == 5 + assert vars(target) == original_attributes + + +def test_unhashable_callables_keep_distinct_explicit_signatures(): + class Callable: + __hash__ = None + + def __init__(self, name): + self.__signature__ = Signature([Parameter(name, Parameter.KEYWORD_ONLY)]) + + def __call__(self, **kwargs): + return kwargs + + first = Callable("left") + second = Callable("right") + first_adapted = callable_method(first) + second_adapted = callable_method(second) + for left, right in [(1, 2), (3, 4)]: + assert first_adapted(left=left, right=right) == {"left": left} + assert second_adapted(left=left, right=right) == {"right": right} + + +def test_partial_callable_preserves_bound_positional_arguments(): + class Callable: + def __call__(self, prefix, value): + return prefix, value + + target = Callable() + wrapped = callable_method(partial(target, "bound")) + assert wrapped(value=7, unrelated=True) == ("bound", 7) + assert wrapped(value=9, unrelated=False) == ("bound", 9) + + +def test_callable_and_bound_call_method_have_equivalent_signatures(): + target = Guard() + assert SignatureAdapter.from_callable(target) == SignatureAdapter.from_callable( + target.__call__ + ) + + +async def test_unhashable_guard_with_relocated_nested_callbacks(sm_runner): + entered = [] + + class UnhashableGuard: + __hash__ = None + + def __call__(self, allowed): + return allowed + + guard = UnhashableGuard() + + class Machine(StateChart): + catch_errors_as_events = False + + class regions(State.Parallel): + class left(State.Compound): + start = State(initial=True) + done = State(final=True) + go = start.to(done, cond=guard) + + @done.enter + def record(self): + entered.append("left") + + class right(State.Compound): + waiting = State(initial=True) + finished = State(final=True) + go = waiting.to(finished) + + @finished.enter + def record(self): + entered.append("right") + + machine = await sm_runner.start(Machine) + await sm_runner.send(machine, "go", allowed=True) + assert sorted(entered) == ["left", "right"] + assert vars(guard) == {} + + +async def test_zero_argument_guard_and_callable_action(sm_runner): + calls = [] + + class Allowed: + __slots__ = () + + def __call__(self): + return True + + class Record: + __slots__ = () + + def __call__(self, machine, event): + calls.append((machine, event)) + + class Machine(StateChart): + catch_errors_as_events = False + a = State(initial=True) + b = State(final=True) + go = a.to(b, cond=Allowed(), on=Record()) + + machine = await sm_runner.start(Machine) + await sm_runner.send(machine, "go") + assert "b" in machine.configuration_values + assert calls == [(machine, "go")] + + +def test_partial_callable_preserves_explicit_signature(): + class Callable: + __signature__ = Signature( + [ + Parameter("prefix", Parameter.POSITIONAL_OR_KEYWORD), + Parameter("value", Parameter.KEYWORD_ONLY), + ] + ) + + def __call__(self, *args, **kwargs): + return args, kwargs + + target = Callable() + wrapped = callable_method(partial(target, "bound")) + assert wrapped(value=7, unrelated=True) == (("bound",), {"value": 7}) + assert wrapped(value=9, unrelated=False) == (("bound",), {"value": 9}) + assert not hasattr(target.__signature__, "is_coroutine") + + +def test_callable_without_explicit_signature_uses_call_method(): + class Callable: + __signature__ = None + + def __call__(self, value): + return value + + wrapped = callable_method(Callable()) + assert wrapped(value=7, ignored=True) == 7