Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #64742

Re: should I transfer 'iterators' between functions?

From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: should I transfer 'iterators' between functions?
Date 2014-01-25 07:55 -0500
References <6ad4232c-a8d9-4195-9edd-65c0e35923a7@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.5974.1390654524.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 1/25/14 1:37 AM, seaspeak@gmail.com 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?
>
> def test():
>      l = [1, 2, 3, 4, 5, 6, 7, 8]
>      return iter(l)
> def main():
>      for i in test():
>          print(i)
>
>

The two things to understand here are names, and values.  When you leave 
the function test, the name l goes away, because it is a locally scoped 
name.  It referred to a value, your list.  But values have reference 
counts, and are not reclaimed until their reference count drops to zero.

Your function is returning a value, a listiterator, and that 
listiterator refers to the list, so the list won't be reclaimed.

Names have scopes but no types.  Values have types, but no scope.  They 
live as long as they are referred to by something.

This is covered in more detail here: 
http://nedbatchelder.com/text/names.html


-- 
Ned Batchelder, http://nedbatchelder.com

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

should I transfer 'iterators' between functions? seaspeak@gmail.com - 2014-01-24 22:37 -0800
  Re: should I transfer 'iterators' between functions? Chris Angelico <rosuav@gmail.com> - 2014-01-25 17:43 +1100
  Re: should I transfer 'iterators' between functions? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-01-25 06:45 +0000
  Re: should I transfer 'iterators' between functions? Ned Batchelder <ned@nedbatchelder.com> - 2014-01-25 07:55 -0500
  Re: should I transfer 'iterators' between functions? Ned Batchelder <ned@nedbatchelder.com> - 2014-01-25 07:56 -0500
  Re: should I transfer 'iterators' between functions? Peter Otten <__peter__@web.de> - 2014-01-25 14:32 +0100

csiph-web