[Tutor] Generator function question?
John Clark
clajo04 at mac.com
Sat May 7 13:28:34 CEST 2005
Hello,
I am working on learning Python and writing some console applications to
apply what I am learning - I am using a generator function to implement a
status indicator as follows:
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
def Test2():
for y in range(1, 10):
sys.stderr.write('\b \nTesting'+str(y)+'\t')
Test1()
Test2()
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
More information about the Tutor
mailing list