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
> 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
Aucun commentaire:
Enregistrer un commentaire