Co-routines

Michael Sparks zathras at thwackety.com
Thu Jul 17 11:11:58 EDT 2003


On Thu, 17 Jul 2003 thewrights at ozemail.com.au wrote:
> >From the python grammar:
>
>     funcdef    ::= "def" funcname "(" [parameter_list] ")" ":" suite
>
> I want the statements in <suite> to be executed [lockstepped]
> on a statement by statement basis, with no particular restrictions on
> *what* those statements are.

Tricky - without jumping in before the code is compiled by python or
similar then I can't think of any way to do this. I can however think of a
perlesque way to do it. (ie should work, might not be considered nice)

One possible way out is if you're willing to change the way you write &
run code /slightly/.

Rather than write:
   def func(arg):
      arg.foo()
      arg.bla()
      while arg.foobar():
         print arg.state()
         arg.bla()

If you write this in your source files:
   def func(arg):
      arg.foo();
      arg.bla();
      while arg.foobar():
         print arg.state();
         arg.bla();

Before you run these files you could pre-process them to change all
occurances of ";" to "; yield <num>". Clearly you could do this
pre-processing in python and then exec the code. ie your preprocessor
would change the above code fragment to:

   def func(arg):
      arg.foo(); yield 1
      arg.bla(); yield 2
      while arg.foobar():
         print arg.state(); yield 3
         arg.bla(); yield 4

Then to run your functions in lockstep, you simply:

gens = [ x() for x in [func1, func2, func3, func4 ]
while gens:
   newgens = []
   foreach gen in gens:
      try:
         gen.next()
         newgens.append(gen)
      except StopIteration:
         pass
   gens = newgens

(Working on the assumption the generators for different functions will run
for differing periods of time)

About the only way I can see this working "simply" is using this sort of
pre-processing trick. I doubt it'd be considered Pythonic. (Personally I
view as more like a perlesque trick) It does however leave your code
looking single threaded (in fact I suppose it still is if you don't
preprocess it), and doesn't require any odd code structuring. (It does
require care if you use semi-colons inside strings/etc)

HTH,

Michael.






More information about the Python-list mailing list