[IPython-user] Strange behaviour of generator in IPython
Karl Pflästerer
sigurd at 12move.de
Thu Aug 14 15:55:49 CDT 2003
Hi,
I searched the list archive and the bug tracker but found nothing about
that issue (well I'm not sure if it's a bug so I report it first here).
Python is 2.3 (Cygwin-version).
If I write a simple generator like that:
In [60]: def counter(start=1, step=1):
....: c = [start]
....: while 1:
....: yield c[0]
....: c[0] += step
....:
In [61]: c = counter()
In [62]: [c.next() for i in range(10)]
Out[62]: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
In [63]: [c.next() for i in range(10)]
Out[63]: [31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
In the default interactive python I get:
$ python
Python 2.3 (#1, Aug 1 2003, 15:01:23)
[GCC 3.2 20020927 (prerelease)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def counter(start=1, step=1):
... c = [start]
... while 1:
... yield c[0]
... c[0] += step
...
>>> c = counter()
>>> [c.next() for i in range(10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [c.next() for i in range(10)]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>>
The output in default Python is the one I expected. What's wrong here?
If I add a print statement after the yield statement
In [3]: def counter(start=1, step=1):
...: c = [start]
...: while 1:
...: yield c[0]
...: print c[0]
...: c[0] += step
...:
In [4]: c = counter()
In [5]: [c.next() for i in range(5)]
1
2
3
4
5
6
7
8
9
Out[5]: [6, 7, 8, 9, 10]
Somehow next() gets called two times range(n) and not range(n)
KP
--
And has thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!'
He chortled in his joy. "Lewis Carroll" "Jabberwocky"
More information about the IPython-user
mailing list