pytransitions / transitions

A lightweight, object-oriented finite state machine implementation in Python with many extensions
MIT License
5.49k stars 524 forks source link

Problems with Machine init #545

Closed VKSolovev closed 2 years ago

VKSolovev commented 2 years ago

Thank you for taking the time to report a bug! Your support is essential for the maintenance of this project. Please fill out the following fields to ease bug hunting and resolving this issue as soon as possible:

Impossible to init machine on model with castom implementation of eq

from transitions import Machine

class C:
    def __init__(self):
        Machine(self, states=['state'], transitions=[], initial='state')

    def __eq__(self, other):
        if not isinstance(other, C):
            raise NotImplemented
        return True

c = C()

This raises NotImplemented. The problem is in core 604

mod = self if mod == 'self' else mod

When mod is compared with the string the eq of C raises error. It can be replaces with

mod = self if mod is 'self' else mod
aleneum commented 2 years ago

Hello @VKSolovev,

x is "a string" will raise a SyntaxWarning in Python 3.8 and it seems like this was elevated to a SyntaxError in Python 3.9 and beyond (see Dennis Sweeney's comment). Maybe there is another way to enable easier override of __eq__.

I removed the bug label since using == is intended behaviour (as of now).

aleneum commented 2 years ago

I moved 'self' to a class variable. This may cause some minor inconvenience for users that would like to add a couple of models AND the machine itself ([mod1, mod2, Machine.self_literal]) but an identity check feels like the better approach. I pushed this change to the master branch with af7008e. Let me know if this solves your issue.

aleneum commented 2 years ago

I assume this issue has been solved by this commit since there has not been any feedback. Feel free to comment anyway and I will reopen the issue if necessary.