Python tricks

Robert Latest boblatest at yahoo.com
Mon Jan 12 22:40:47 CET 2009


RajNewbie wrote:
>    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.

Maybe you should call the counter variable something meaningful instead
of -- of all things -- "i", which is idiomatic for soething entirely
else. And add a comment, and be done with it.

>    The solution that I had in mind is:
>    while True:
>      ...
>      if <condition>: break
>      if inifinte_loop(): raise infiinte_loop_exception

This is a lot less understandable because whoever is working with your
code will now have to check an additional function  rather than a
pretty self-explanatory variable increment.

robert



More information about the Python-list mailing list