On Thu, 19 Jan 2006 23:16:57 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:

>Carl Cerecke wrote:
>> Carl Cerecke wrote:
>>>Ah. Well, my post suggested, as one option, the callables call
>>>each other directly.
>> 
>> Doh! No I didn't. And they shouldn't. Otherwise the call stack
>> gets out of hand. But I did suggest that each callable representing a 
>> state set a global variable, just before it returns, to the callable 
>> representing the next state to be called. Still no map required. Just a 
>> while loop. In any case, the function call/return is wasted cycles.
>
>I believe the more modern approach to this is to use generators in some 
>way, yield each other as the next state.  This way you avoid all almost 
>all the function call overhead (the part that takes significant time, 
>which is setting up the stack frame) and don't have to resort to 
>bytecode hacks for better performance.
>
>Of course, if you have a state machine with many small states each doing 
>a tiny bit of processing and you're still concerned over performance, 
>you probably should be looking into Pysco or Pyrex and avoid making your 
>code really unreadable.
>
How about something like

 >>> actions = dict(
 ...    a=compile('print "A"; state="b"','','exec'),
 ...    b=compile('print "B"; state="c"','','exec'),
 ...    c=compile('print "C"; state=None','','exec')
 ... )
 >>> state = 'a'
 >>> while state: eval(actions[state])
 ...
 A
 B
 C

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to