Hacker News new | past | comments | ask | show | jobs | submit | webexcess's comments login

Yes, your code is the same as the first example generator with a single yield in a loop.

The same conversion for the later examples with multiple yield statements, try: except: or try: finally: will be much hairier, though.



Very cool, thanks.


Thank you, I hadn't seen that. I've added that link to the bottom of my article.


You use "assert gen.next() is None", but asserts might be dropped by optimizations, see e.g. http://docs.python.org/release/2.5.2/ref/assert.html - and your code will break.

assert should only be used for debugging, and only for things that should never happen. side effects on assert is a no-no. (Also in C)


That's a feature!

Seriously though, not being able to define a serialization method can be a limitation. However, it is always possible to turn a generator into an iterator class with whatever methods you like, but the code may end up looking totally different.


To me it only looks like a limitation.

So yeah, you can write a custom class. But you will need to add a custom "save state" and "load state" in your class' __iter__ method. So all the benefits go away.


It should be possible to create the exact same classes dynamically, without using exec. The only advantage I can see of the exec is that the class template string makes it a little clearer what the equivalent "normal" class definition would look like.

There are other drawbacks to exec though, some people have disabled exec for security reasons and it's opaque to things like pypy.


You can use python -i to enter interactive mode after executing a script. Maybe I should clarify that part


Ooh, dunno why I thought that wasn't supported in IPython too before, but it is. Lovely.


Good point. I didn't address this adequately.

The usual #python response to people using the array module was to instead consider NumPy (with its excellent arrays) or use normal lists and PyPy to make it fast.


Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: