Python tricks

Nick Craig-Wood nick at craig-wood.com
Tue Jan 13 05:32:08 EST 2009


Scott David Daniels <Scott.Daniels at Acm.Org> wrote:
>  RajNewbie wrote:
> > On Jan 12, 6:51 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
>      [a perfectly fine reply which is how I'd solve it]
>  >> RajNewbie wrote:
> >>> ... 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?
> > ...
> > But, I still feel it would be much more aesthetically pleasing if I
> > can call a single procedure like
> > if infinite_loop() -> to do the same.
> > Is it somehow possible? - say by using static variables, iterators --
> > anything?
> 
>  Yes, it is possible.  After:
> 
>       def Fuse(count, exception):
>           for i in range(count):
>               yield None
>           raise exception
> 
>  You can do your loop as:
>       check_infinite = Fuse(200, ValueError('Infinite Loop')).next
>       while True:
>           ...
>           check_infinite()

Or related to the above and the original proposal

class InfiniteLoopError(Exception):
    """An 'infinite' loop has been detected"""

def infinite_loop(max=200):
    for i in xrange(max):
        yield i
    raise InfiniteLoopError()

Use it like this

for i in infinite_loop():
    if i > 10:
        break
    print "iteration", i

or

for i in infinite_loop(10):
    print "iteration", i

>  but I agree with Tim that a for ... else loop for the limit is
>  clearer.

Probably yes

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list