Because that's totally a thing you wanted.
Loop
lets you write C-style loops in the bodies of Python classes.
>>> from loop import Loop
>>> class For(Loop):
... x = 0; x < 5; ++x
... print("Body:", x)
...
Body: 0
Body: 1
Body: 2
Body: 3
Body: 4
Inside the body of the loop, you can call break_()
and continue_()
to
break and continue the loop execution.
>>> class For(Loop):
... x = 0; x < 5; ++x
... if x == 2:
... print("Skipping 2")
... continue_()
... print("Body:", x)
...
Body: 0
Body: 1
Skipping 2
Body: 3
Body: 4
>>> class For(Loop):
... x = 0; x < 5; ++x
... if x == 2:
... print("Breaking on 2")
... break_()
... print("Body:", x)
...
Body: 0
Body: 1
Breaking on 2
Loop
correctly handle tricky edge cases.
If the loop condition is initially False, the loop body is never executed.
>>> iters = []
>>> class For(Loop):
... x = 0; x > 100; ++x
... iters.append(x)
...
>>> iters
[]
Loop
bodies can refer to local variables of enclosing functions.
>>> def func():
... iters = []
... class For(Loop):
... x = 0; x < 5; ++x
... iters.append(x)
... return iters
...
>>> func()
[0, 1, 2, 4, 4]