

Python Generator Tricks - RiderOfGiraffes
http://linuxgazette.net/100/pramode.html

======
metachris
Interesting post -- I've come to appreciate linuxgazette as a pretty good
resource.

As a minor sidenote, I personally think 4 spaces for indentation makes the
code more readable.

~~~
bmelton
I do almost all of my code editing in regular text editors, Vi or Notepad,
usually. 4 spaces is impossible for me.

Why do you feel that 4 spaces is better than 5, which is usually the number of
spaces represented by \t?

~~~
silvajoao
In my particular instance of the Universe, \t is usually represented by 8
spaces. I still prefer 4 though.

~~~
bmelton
As it happens, I can't count. \t IS 8, though hopefully there's some other
reason I got downvoted to -4 than that.

Still though, my question remains. Is there a particular reason you prefer 4?
Does it affect your workflow in any way or does it just 'look better' in the
abstract? I'm curious.

~~~
silvajoao
I use a single tab for indentation, and too much exposure to Java and the
Eclipse default indentation size (4 spaces per tab) made me used to it. I also
find it easier to look at python code indented by 4 spaces per tab. Since I
also tend to limit line length to 80 chars, 8-spaces tabs would quickly use up
precious space.

Linus disagrees:
[http://lxr.linux.no/linux+v2.6.35.7/Documentation/CodingStyl...](http://lxr.linux.no/linux+v2.6.35.7/Documentation/CodingStyle#L18)

------
jgresula
Here is a great practical intro to generators: Generator Tricks for Systems
Programmers - <http://www.dabeaz.com/generators-uk/GeneratorsUK.pdf>

------
RiderOfGiraffes
Reading this item : <http://news.ycombinator.com/item?id=1738906> : in which
generators are discussed in comparison with the usual operations from
functional programming languages, I was reminded of this article. Hence the
submission.

------
viraptor
Here's also an interesting blog post from the creator of Diesel -
<http://blog.jamwt.com/2010/08/04/generators-and-back-again/> It's about using
generators for trivial task scheduling.

------
praptak
Python's own @contextmanager decorator (
[http://docs.python.org/library/contextlib.html#contextlib.co...](http://docs.python.org/library/contextlib.html#contextlib.contextmanager)
) uses generators in quite a clever way. You can grok quite a lot about Python
generators by trying to figure out what @contextmanager actually does under
the hood.

------
bravura
Please allow me to pickle simple generators. Otherwise, I have to go through
all sorts of contortions:

    
    
       http://metaoptimize.com/blog/2009/12/22/why-cant-you-pickle-generators-in-python-workaround-pattern-for-saving-training-state/

------
adambyrtek
The article is from 2004, so it doesn't mention modern features like generator
expressions, context managers or co-routines (PEP 342). I suspect it was
upvoted so much mostly because of the SICP reference.

~~~
gkelly
It's also importing from __future__, which isn't necessary anymore.

