Python tricks
Tim Chase
python.list at tim.thechases.com
Mon Jan 12 08:51:17 EST 2009
> My code has a lot of while loops of the following format:
> while True:
> ...
> if <condition>: break
>
> The danger with such a code is that it might go to an infinite loop
> - if the <condition> never occurs.
> Is there a way - a python trick - to have a check such that if the
> loop goes for more than x number of steps, it will cause an exception?
>
> I do understand that we can use the code like -
> i = 0
> while True:
> i++
> if i > 200: raise infinite_Loop_Exception
> ...
> if <condition>: break
>
> But I am not very happy with this code for 3 reasons
> 1. Verbosity (i=0 and i++) which doesnt add to the logic
> 2. The loop now has dual focus. - incrementing i, etc.
> 3. <most important> A person looks into the code and thinks 'i'
> has special significance. His/her mind will be focused on not the
> actual reason for the loop.
My first thought would be to simply not use "while True":
INFINITE_LOOP_COUNT = 200
for _ in xrange(INFINITE_LOOP_COUNT):
do_something()
if <condition>: break
else:
raise InfiniteLoopException
> The solution that I had in mind is:
> while True:
> ...
> if <condition>: break
> if inifinte_loop(): raise infiinte_loop_exception
>
> Wherein infinite_loop is a generator, which returns true if i > 200
> def infinite_loop():
> i = 0
> while i < 200:
> i++
> yield False
> yield True
>
> Could somebody let me know whether this is a good option?
To do this, you'd need to do the same sort of thing as you do
with your i/i++ variable:
i = infinite_loop()
while True:
...
if <condition>: break
if i.next(): raise InfiniteLoopException
which doesn't gain much, and makes it a whole lot more confusing.
> Could someone chip in with other suggestions?
As an aside: the phrase is "chime in"[1] (to volunteer
suggestions) "Chip in"[2] usually involves contributing money to
a common fund ("care to chip in $10 for Sally's wedding gift from
the office?" where the pool of money would then be used to buy
one large/expensive gift for Sally)
-tkc
[1]
http://www.thefreedictionary.com/chime+in
[2]
http://www.english-test.net/forum/ftopic1768.html
More information about the Python-list
mailing list