[Python-Dev] generator/microthread syntax

Wade Brainerd wade at treyarch.com
Tue Nov 18 19:12:13 EST 2003

Hello, I'm working on a game engine using Python as the scripting 
language and have a question about generators. 

I'm using what I guess are called 'microthreads' as my basic script 
building block, and I'd like to know if there is some kind of syntax 
that could make them clearer, either something in Python already or 
something that could be added.

Here's an example script that illustrates the problem.

from jthe import *

def darlene_ai(self):
    while True:
        for x in wait_until_near(player.po.w,self.po.w): yield None


        for x in wait_face_each_other(player.po,self.po): yield None

        if not player.inventory.has_key("papers"):
            for x in say("Hi, I'm Darlene!  I found these papers,\ndid 
you lose them?"): yield None
            for x in say("Hey, I'm new to this town, wanna go out 
sometime?"): yield None


        if not player.inventory.has_key("papers"):

        for x in wait(2.5): yield None

Now in our in-house script language the above code would look very 
similar, only without the

for x in <call>: yield None

constructs.  Instead, subroutines with a wait_ prefix execute yield 
statements which are automatically propogated up the call stack all the 
way to the thread manager. 

Is there anything to be done about this in Python?  I can see it 
implemented three ways:

1. A new declaration for the caller function.  yield statements 
propogate up the call stack automatically until the first 
non-microthread function is found.

microthread darlene_ai(self):

2. A special kind of exception.  The wait_ function throws an exception 
containing the current execution context, which is caught by the thread 
manager and then later resumed.  Generators would not be used at all.

3. A new yield-like keyword, which assumes that the argument is a 
generator and whose definition is to return the result of 
argument.next() until it catches a StopIteration exception, at which 
point it continues.  This is just shorthand for the for loop, and would 
look something like:

def darlene_ai(self):
    while True:
         wait until_near(player.po.w,self.po.w)

Anyway, thanks for your time, and for the amazing language and modules.


More information about the Python-Dev mailing list