Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info>:

> I can only imagine you mean something like this:
>
> class Outer:
>     class InnerOne:
>         ...
>
>     class InnerTwo:
>         ...
>
>     class InnerThree:
>         ...
>

No, I mean this:

   class StateMachine:
       def __init__(self):
            sm = self

            class Idle:
                def connect(self):
                    ...
                    sm.set_state(Connecting)
                    ...

            class Connecting:
                def poll(self):
                    if sm.sock....:
                        sm.set_state(Connected)

            class Connected:
                ...

            self.set_state(Idle)

        def set_state(self, state):
            self.state = state()

        def connect(self):
            self.state.connect()

        def poll(self):
            self.state.poll()

        ...

>> Often a state machine has numerous states but the typical execution
>> path only visits a few of them. However, the pattern calls for
>> declaring classes (or instances) for all states in the state machine
>> constructor. Switch statements make it possible to avoid this
>> creation overhead.
>
> How do you avoid creating the classes or instances? If they haven't
> been created, how can the compiler reference them?

The comparison is between three techniques:

 1. dict dispatch -- considered barely readable by me

 2. the state pattern (see "class StateMachine" above)

 3. sentinel state objects with switches

What I said in the above paragraph is that state machines can be written
using the state pattern (thus avoiding the need for switch statements).
However, the pattern often consumes lots of time and space.


Marko
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to