static keyword

Robert Brewer fumanchu at amor.org
Thu Apr 29 18:59:52 EDT 2004


I wrote:
> > >>> def foo():
> > ... 	i = 10
> > ... 	print "First pass"
> > ... 	while True:
> > ... 		i += 1
> > ... 		yield i
> > ... 		
> > >>> g = foo()
> > >>> g.next()
> > First pass
> > 11
> > >>> g.next()
> > 12

and Nick Jacobson replied:
> Yes, that is excellent.  Thank you very much. :)
> 
> The good news: you can reset all your "static" data whenever you want,
> by calling foo().  Can't do that in C.
> 
> The bad news: I just hope I don't forget and call foo() instead of
> g.next().
> I would rather the command foo() by default call the next iteration,
> and, say, foo().reset() would recall the function from scratch.

It all comes down to naming, for me. When you make a generator, name it
as a generator, not as one of the produced items. That is, for the
above, you would never name it next_item(), because that gives the wrong
idea:

>>> g = next_item()
>>> next_item()
<generator object at ...>

...as you can see, the last line throws you because you didn't get what
you might expect from a functional perspective. However, if I name it
count_from_eleven, which would then read as:

>>> g = count_from_eleven()
>>> count_from_eleven()
<generator object at ...>

...that problem goes away, because the last call doesn't "read" right.
You'd never write it, because the name signals to you that you're doing
The Wrong Thing.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list