[Tutor] Generator function question?

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Sat May 7 14:17:22 CEST 2005


Quoting John Clark <clajo04 at mac.com>:

> import sys
> 
>  def neverEndingStatus(currentChar_ = '|'):
>  while 1:
>   if currentChar_ == '|':
>    currentChar_ = '\\'
>   elif currentChar_ == '\\':
>    currentChar_ = '-'
>   elif currentChar_ == '-':
>    currentChar_ = '/'
>   elif currentChar_ == '/':
>    currentChar_ = '|'
>   yield currentChar_
>  
> 
> x = neverEndingStatus()
> 
> def Test1():
>  for w in range(1, 100):
>  sys.stderr.write('\b'+x.next())
>  for z in range(1, 10000):
>  z = z + 1

One of the big uses for generators is in loops.  eg:

>>> import time
>>> def nes():
...  chars = ('|', '\\', '-', '/')
...  i = 0
...  while True:
...   yield chars[i]
...   i = (i + 1) % len(chars)
...
>>> for c in nes():
...  print c,
...  time.sleep(0.5)
...
| \ - / | \ - / | \ - / | \ - / | \ - / | \ ...

Of course, you'll need _some_ way of breaking out of the loop eventually (either
a 'break' statement in the for loop, or something in nes() to raise
StopIteration, which will cause the for loop to exit naturally).

-- 
John.


More information about the Tutor mailing list