[Tutor] Generator function question?

Max Noel maxnoel_fr at yahoo.fr
Sat May 7 14:00:03 CEST 2005


On May 7, 2005, at 12:28, John Clark wrote:

> My question - the creation of the global variable x seems kludged -  
> when I
> first started with this I thought I was going to be coding  
> something like
> sys.stderr.write('\b'+neverEndingStatus()) but that just returns  
> '\' each
> time and I now recognize why.  I am just thinking there has to be a  
> way to
> encapsulate the generator function, the global variable and  
> the .next() call
> so that it is much cleaner in the client code.
>
> My guess is that I could create a class, override the __call__  
> method and
> get to the point where my code is something like:
> sys.stderr.write('\b'+statusClass()) but that seems to be heavy
> (implementing a class) and intrusive (overriding the __call__  
> method seems a
> bit heavy handed) - my reluctance may be just because I am less  
> familiar
> with those particular constructs in Python, but it still feels like  
> I should
> be able to do this more cleanly without that.
>
> Also - I look at the code in the neverEndingStatus() function and I  
> just
> _know_ there has to be a better way to write that - it's just not  
> coming to
> me.  Any suggestions are embarrassingly appreciated...
>
> Thanks,
> -jdc
>

     This is (IMO) more elegant:

def neverEndingStatus():
     index = 0
     statusChars = ['|', '\\', '-', '/']
     while True:
         yield statusChars[index]
         index = (index + 1) % 4


     As for how to access it, use a for loop (for i in  
neverEndingStatus()). xrange, for example, is a generator function.

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting  
and sweating as you run through my corridors... How can you challenge  
a perfect, immortal machine?"



More information about the Tutor mailing list