kj wrote:

I'm coaching a group of biologists on basic Python scripting.  One
of my charges mentioned that he had come across the advice never
to use loops beginning with "while True".  Of course, that's one
way to start an infinite loop, but this seems hardly a sufficient
reason to avoid the construct altogether, as long as one includes
an exit that is always reached.  (Actually, come to think of it,
there are many situations in which a bona fide infinite loops
(typically within a try: block) is the required construct, e.g.
when implementing an event loop.)

I use "while True"-loops often, and intend to continue doing this
"while True", but I'm curious to know: how widespread is the
injunction against such loops?  Has it reached the status of "best
practice"?

TIA!

kynn
This thread has gotten a lot of posts concerning programming practices and dogma alike. I'd like to add a personal use of `while True:` that has nothing to do with either best practices or dogma. I use python a *lot* to do day-to-day tasks in an engineering lab. I use it to control, log, or otherwise converse with rs232 based gear, as well as use it to back up or organize documents, etc... (lo and behold, I use this scripting language to write little scripts here and there). Don't get me wrong, I also write full blown control/logging apps with python, but that is only 10% of my usage. Whenever I need to quickly log something (serial output of a device) quickly, I find myself writing this in the python REPL:
import serial
comport = serial.Serial('COMx', timeout=1)
while True:
   get = comport.readline()
   f.open("blah", 'a')
   f.write(get)
   f.close()

It is short enough that I don't see the need to write my own module. Sometimes I even add a little regexp based filtering -- which adds 2 lines total. When I am done logging I just give 'er a CTRL-C and be done with it. It is also a hell of a lot less buggy and error prone than hyperterminal, which my boss uses to do the same thing. I think this is a perfect example of `while True:` that works damn well, and there isn't anything that can replace its simplicity. Programming practices be damned, it is invaluable, and I would recommend doing it in my situation to any person, regardless of programming experience. Food for thought.

-Jack
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to