Python generators in Java?
Alan Kennedy
alanmk at hotmail.com
Mon Nov 15 11:44:46 EST 2004
[Robert Oschler]
> Preamble:
>
> - I know this is the Python forum
> - I know about (and have used) Jython
>
> I already posted this question in comp.lang.java. But after a week I
> have still not received a single reply.
>
> One of my favorite Python features is generators. I have to use Java
> for one particular project (it happens). I would like to have
> something at least close to Python's generators for the project.
Hi Robert,
Hmm, I don't see a direct question in your post, so I'll just assume
that you're generally inquiring about generator style functionality in java.
If you're looking to achieve the execution efficiency of python
generators, e.g. in terms of processing sequences one value at a time
rather than generating the entire sequence and then processing, then you
should look at java iterators, which are designed specifically for this
purpose.
Note that java 1.5 brings new syntactic features which support
iterators, e.g. short-hand for loops like this
public int sumArray(int array[]) {
int sum = 0;
for(int i : array) {
sum += i;
}
return sum;
}
Quite pythonic, IMHO.
http://java.sun.com/developer/technicalArticles/releases/j2se15langfeat/
However, if you're looking for the resumable-functions aspect of
generators, you're out of luck: java doesn't not support them. But note
that a java iterator will still very likely be more efficient than a
python generator, albeit that the code won't be as clean.
Note that there is a currently a proposal from the codehaus people to
add continuations to java, which could make both generators and full
coroutines possible in java.
http://docs.codehaus.org/display/continuation/Home
Lastly, it would probably be easier to discuss this subject if you gave
an example of the type of thing you want to do, and some reasons why you
want to do it that way. Post some python: maybe the java would be
straightforward.
Regards,
--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
More information about the Python-list
mailing list