Why don't generators execute until first yield?
castironpi at gmail.com
castironpi at gmail.com
Wed May 7 09:49:36 EDT 2008
On May 7, 7:37 am, Marco Mariani <ma... at sferacarta.com> wrote:
> Duncan Booth wrote:
> > Perhaps if you'd copied all of my code (including the decorator that was
> > the whole point of it)...
>
> Sure, I missed the point. Python's > symbols become quoting levels and
> mess up messages.
>
> Anyway, I would loathe to start execution of a generator before starting
> to iterate through it. Especially when generators are passed around.
> The current behavior makes perfect sense.
Question:
>>> def f( ):
... print 0
... while 1:
... yield 1
...
>>> g= f( )
>>> g.next( )
0
1
>>> g.next( )
1
>>> g.next( )
1
This might fit the bill:
>>> def dropfirst( h ):
... h.next( )
... return h
...
>>> g= dropfirst( f( ) )
0
>>> g.next( )
1
>>> g.next( )
1
>>> g.next( )
1
However as dropfirst is dropping a value, both caller -and- cally have
to designate a/the exception. Hold generators are better "first-
dropped", and you hold 'next' inherently causes side effects. @greedy
(from earlier) frees the caller of a responsibility/obligation.
What can follow without a lead?
The definitions may lean harder on the 'generation' as prior to the
'next': generators inherently don't cause side effects.
Or hold, first-dropped is no exception:
>>> special= object( )
>>> def f( ):
... print 0
... yield special
... while 1:
... yield 1
...
>>> g= f( )
>>> g.next( )
0
<object object at 0x00980470>
>>> g.next( )
1
>>> g.next( )
1
>>> g.next( )
1
More information about the Python-list
mailing list