[Python-ideas] BUG in standard while statement

David Blaschke dwblas at gmail.com
Wed Sep 9 19:30:38 CEST 2015


while repeat(2): creates a new repeat instance each time through the
loop and initializes the variable as 2 each time through the loop i.e.
repeat(2) returns a new, different instance each time.

On 9/9/15, Stephan Sahm <Stephan.Sahm at gmx.de> wrote:
> Dear all
>
> I found a BUG in the standard while statement, which appears both in python
> 2.7 and python 3.4 on my system.
>
> It usually won't appear because I only stumbled upon it after trying to
> implement a nice repeat structure. Look:
> ​```​
> class repeat(object):
>     def __init__(self, n):
>         self.n = n
>
>     def __bool__(self):
>         self.n -= 1
>         return self.n >= 0
>
>     __nonzero__=__bool__
>
> a = repeat(2)
> ```
> the meaning of the above is that bool(a) returns True 2-times, and after
> that always False.
>
> Now executing
> ```
> while a:
>     print('foo')
> ```
> will in fact print 'foo' two times. HOWEVER ;-) ....
> ```
> while repeat(2):
>     print('foo')
> ```
> will go on and go on, printing 'foo' until I kill it.
>
> Please comment, explain or recommend this further if you also think that
> both while statements should behave identically.
>
> hoping for responses,
> best,
> Stephan
>


-- 
With the simplicity of true nature, there shall be no desire.
Without desire, one's original nature will be at peace.
And the world will naturally be in accord with the right Way.  Tao Te Ching


More information about the Python-ideas mailing list