[issue32768] object.__new__ does not accept arguments if __bases__ is changed

Alexey Muranov report at bugs.python.org
Tue May 7 03:40:03 EDT 2019


Alexey Muranov <alexey.muranov at gmail.com> added the comment:

Here is a use case for writable bases:

https://stackoverflow.com/q/56007866

class Stateful:
    """
    Abstract base class for "stateful" classes.

    Subclasses must implement InitState mixin.
    """

    @staticmethod
    def __new__(cls, *args, **kwargs):
        super_new = super(__class__, __class__).__new__

        # XXX: see https://stackoverflow.com/a/9639512
        class CurrentStateProxy(cls.InitState):
            @staticmethod
            def _set_state(state_cls=cls.InitState):
                __class__.__bases__ = (state_cls,)

        class Eigenclass(CurrentStateProxy, cls):
            @staticmethod
            def __new__(cls, *args, **kwargs):
                cls.__new__ = None  # just in case
                return super_new(cls, *args, **kwargs)

        return Eigenclass(*args, **kwargs)

class StatefulThing(Stateful):
    class StateA:
        """First state mixin."""

        def say_hello(self):
            print("Hello!")
            self.hello_count += 1
            self._set_state(self.StateB)
            return True

        def say_goodbye(self):
            print("Another goodbye?")
            return False

    class StateB:
        """Second state mixin."""

        def say_hello(self):
            print("Another hello?")
            return False

        def say_goodbye(self):
            print("Goodbye!")
            self.goodbye_count += 1
            self._set_state(self.StateA)
            return True

    # This one is required by Stateful.
    class InitState(StateA):
        """Third state mixin -- the initial state."""

        def say_goodbye(self):
            print("Why?")
            return False

    def __init__(self):
        self.hello_count = self.goodbye_count = 0

    def say_hello_followed_by_goodbye(self):
        self.say_hello() and self.say_goodbye()

# ----------
# ## Demo ##
# ----------
if __name__ == "__main__":
    t1 = StatefulThing()
    t2 = StatefulThing()
    print("> t1, say hello:")
    t1.say_hello()
    print("> t2, say goodbye:")
    t2.say_goodbye()
    print("> t2, say hello:")
    t2.say_hello()
    print("> t1, say hello:")
    t1.say_hello()
    print("> t1, say hello followed by goodbye:")
    t1.say_hello_followed_by_goodbye()
    print("> t2, say goodbye:")
    t2.say_goodbye()
    print("> t2, say hello followed by goodbye:")
    t2.say_hello_followed_by_goodbye()
    print("> t1, say goodbye:")
    t1.say_goodbye()
    print("> t2, say hello:")
    t2.say_hello()
    print("---")
    print( "t1 said {} hellos and {} goodbyes."
           .format(t1.hello_count, t1.goodbye_count) )
    print( "t2 said {} hellos and {} goodbyes."
           .format(t2.hello_count, t2.goodbye_count) )

    # Expected output:
    #
    #     > t1, say hello:
    #     Hello!
    #     > t2, say goodbye:
    #     Why?
    #     > t2, say hello:
    #     Hello!
    #     > t1, say hello:
    #     Another hello?
    #     > t1, say hello followed by goodbye:
    #     Another hello?
    #     > t2, say goodbye:
    #     Goodbye!
    #     > t2, say hello followed by goodbye:
    #     Hello!
    #     Goodbye!
    #     > t1, say goodbye:
    #     Goodbye!
    #     > t2, say hello:
    #     Hello!
    #     ---
    #     t1 said 1 hellos and 1 goodbyes.
    #     t2 said 3 hellos and 2 goodbyes.

----------
nosy: +alexey-muranov

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32768>
_______________________________________


More information about the Python-bugs-list mailing list