I don't understand generator.send()

OKB (not okblacke) brenNOSPAMbarn at NObrenSPAMbarn.net
Sat May 14 20:38:47 EDT 2011


Victor Eijkhout wrote:

> #! /usr/bin/env python
> 
> def ints():
>     i=0
>     while True:
>         yield i
>         i += 1
> 
> gen = ints()
> while True:
>     i = gen.next()
>     print i
>     if i==5:
>         r = gen.send(2)
>         print "return:",r
>     if i>10:
>         break
> 
> I thought the send call would push the value "2" at the front of
> the queue. Instead it coughs up the 2, which seems senseless to me.
> 
> 1/ How should I view the send call? I'm reading the manual and
> dont' get it
> 2/ Is there a way to push something in the generator object? So
> that it becomes the next yield expression? In my code I was hoping
> to get 0,1,2,3,4,5,2,6,7 as yield expressions.

    	You can't usefully use send() unless the generator is set up to 
make use of the sent values.  You can't just push values into any old 
generator.  For it to do anything, you need to use assign the result of 
the yield to something within your generator and make use of it.  See 
http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features 
for an example.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown



More information about the Python-list mailing list