state machine and a global variable

Matimus mccredie at gmail.com
Fri Dec 14 13:35:19 EST 2007


On Dec 14, 8:52 am, tuom.lar... at gmail.com wrote:
> Dear list,
> I'm writing very simple state machine library, like this:
>
> _state = None
>
> def set_state(state):
>     global _state
>     _state = state
>
> def get_state():
>     print _surface
>
> but I hate to use global variable. So, please, is there a better way
> of doing this? All I want is that a user has to type as little as
> possible, like:
>
> from state_machine import *
> set_state(3)
> get_state()
>
> I.e., nothing like:
> import state_machine
> my_machine = state_machine.new_machine()
> my_machine.set_state(3)
> my_machine.get_state()
>
> Thanks, in advance!

Personally I _would_ do it the second way. That seems to be the most
appropriate way to do it. However, you can do it the second way and
still get the functionality you desire.


[code in state_machine.py]
class StateMachine(object):
    def __init__(self, state=None):
        if state is None:
            state = "DEFAULT_INIT_STATE"
        self._state = state

    def get_state(self):
        # print self._surface
        return self._state

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

_sm = StateMachine()
set_state = _sm.set_state
get_state = _sm.get_state
[/code]

Matt



More information about the Python-list mailing list