define loop statement?

Benji York benji at benjiyork.com
Sat Feb 18 22:05:52 EST 2006


David Isaac wrote:
> I would like to be able to define a loop statement
> (nevermind why) so that I can write something like
> 
> loop 10:
>     do_something

Here's a flagrant hack:

import sys

VAR_NAME = '__repeat_counter'

def set_repeat_counter(value):
     frame = sys._getframe(2)
     frame.f_locals[VAR_NAME] = value

def get_repeat_counter(value):
     frame = sys._getframe(2)
     if VAR_NAME not in frame.f_locals:
         frame.f_locals[VAR_NAME] = value

     return frame.f_locals[VAR_NAME]

def repeat(limit):
     set_repeat_counter(get_repeat_counter(limit)-1)
     return get_repeat_counter(limit)

while repeat(10):
     print 'OK'

Without more work it doesn't allow nested loops though.

And for the record, if you're worrying about Python's counted loop 
construct you need better things to worry about. 
<insert-smilies-as-appropriate>
--
Benji York



More information about the Python-list mailing list