generator update

14 views
Skip to first unread message

Christian Iversen

unread,
Aug 18, 2013, 3:24:33 PM8/18/13
to pyj...@googlegroups.com
Hello World

Some real progress on generators this time.

This program:

def foo():
x = 10
yield x
x = 5
y = 15
z = x + y
yield z
for x in range(9):
yield x
yield 30

for q in foo():
print q


Can be compiled with the ist/generator HEAD (not pushed to github yet,
needs some code cleanups)

Now, a lot of stuff is not supported, but I think this really proves
that my idea about automatically converting generator functions to state
machines is valid. To give you an idea of how deeply the code is being
transformer, take a look at the compiled js:


load("py-builtins.js");
function foo() {
return generator(function(self) {
switch ((self.state + 1)) {
case 1:
self.__gen_x = int(10);
self.state = 1;
return self.__gen_x;
case 2:
self.__gen_x = $c5;
self.__gen_y = int(15);
self.__gen_z = self.__gen_x.PY$__add__(self.__gen_x,
self.__gen_y);
self.state = 2;
return self.__gen_z;
case 3:
self.$y1 = iter(__builtins__.PY$range($c9));
self.state = 3;
case 4:
self.x = $PY.next(self.$y1);
if ((self.x) !== null) {
return self.x;
} else {
self.state = 4;
}
case 5:
self.state = 5;
return int(30);
case 6:
}
throw __builtins__.PY$StopIteration();
});
}
var q;
for (var $v1 = iter(foo()); (q = $PY.next($v1)) !== null; ) {
__builtins__.PY$print(q);
}



Obviously, you can sort of recognize the original variable names (and
especially the last for loop, which is not yield-code), but clearly this
bears little resemblance to the python code.

There's not much we can do about that, really. I'm all for making
support for compiling against the js "yield" keyword, but it's just not
widely supported enough to be our only solution.

So yeah, interesting progress I think. I'll keep you posted :)

--
Med venlig hilsen
Christian Iversen
Reply all
Reply to author
Forward
0 new messages