should I transfer 'iterators' between functions?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Jan 25 01:45:30 EST 2014
On Fri, 24 Jan 2014 22:37:37 -0800, seaspeak wrote:
> take the following as an example, which could work well. But my concern
> is, will list 'l' be deconstructed after function return? and then
> iterator point to nowhere?
That would be a pretty awful bug for Python, since it would like lead to
a core dump. But no, it works fine, as you can see by trying it at the
interactive interpreter:
py> def test():
... L = [1, 2, 4, 8, 16]
... return iter(L)
...
py>
py> for i in test():
... print(i)
...
1
2
4
8
16
In fact, we don't even need a function to see the same effect:
py> L = [1, 2, 4, 8, 16]
py> it = iter(L)
py> del L
py> L = "something else"
py> for i in it:
... print(i)
...
1
2
4
8
16
Python keeps track of when objects are in use, and does not destroy them
so long as it is in use. In the meantime, you can exit the function,
unbind (delete) the variable, re-assign to something else, whatever, and
you should never get a core dump.
(I've only ever seen a single core dump in Python in 15+ years.)
--
Steven
More information about the Python-list
mailing list