Python tricks

Scott David Daniels Scott.Daniels at Acm.Org
Mon Jan 12 18:34:21 CET 2009

RajNewbie wrote:
> On Jan 12, 6:51 pm, Tim Chase <python.l... at> 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?

1) Please cut down quoted text to as little as needed to
    understand the reply.
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:
but I agree with Tim that a for ... else loop for the limit is clearer.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list