Converting "normal" functions into generators

Jason Orendorff jason at jorendorff.com
Mon Jan 14 09:26:01 EST 2002


> I'd like to be able to convert any arbitary function into a generator,
> "yield"-ing some constant after each statement.
> 
> 
> for the simple case:
> 
> def easy(x):
> 	y = x / 2
> 	z = y / 3 + 5
> 	if y > 10:
> 		return y
> 	else:
> 		return x
> 
> would turn into:
> 
> def easy(x):
> 	y = x / 2
> 	yield AConstantValue
> 	z = y / 3 + 5
> 	yield AConstantValue
> 	if y > 10:
> 		return y
> 	else:
> 		return x

This isn't legal, since you can't yield and then return a value
in the same function.

If you're using this just for debug purposes, consider pdb instead.
If you're using it to run different functions in parallel,
threads are (for now) your best alternative.  (What else are you
using this for?)

Probably the best way to instrument Python code like this is to
walk the AST.  Your goal of having something added "after each
*statement*" underscores your need to make your changes after the
parser's first pass.  And hacking the AST shouldn't be that bad.
I think your code will be surprisingly short.

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list