frange() question

Carsten Haese carsten at uniqsys.com
Sat Sep 22 22:50:03 CEST 2007

```On Sat, 2007-09-22 at 18:21 +0000, John J. Lee wrote:
> Carsten Haese <carsten at uniqsys.com> writes:
> > The second half of my post illustrates a difference of opinion about
> > what constitutes a generator function. You state that frange() is not a
> > generator function because it doesn't use yield, but it behaves like
> > one. My point is that it *is* a generator function because the generator
> > expression is merely syntactic sugar for an equivalent for/yield loop.
>
> Seems to me that's a definitional thing, with no conceptual content,
> so "difference of opinion" seems an odd choice of words.  It would be
> nice to nail the definitions down.  Do the Python docs do that?
>
>
> > Of course, the distinction of whether frange() *is* a generator function
> > or merely *behaves* as one is immaterial in practice, and we can both be
> > right in the absence of a formal definition of what a generator function
> > is. PEP 255 says "A function that contains a yield statement is called a
> > generator function," but that was written before generator expressions
> > were introduced.
>
> Ah, they do -- thanks.  Though I'm now left puzzled why you express
> your "difference of opionion" above...

It's a matter of opinion whether the excerpt from the PEP constitutes
the formal definition of what a generator function is or isn't. A formal
definition needs conditions that are both sufficient and necessary. The
PEP only says that having a yield statement is sufficient for making a
generator function. It doesn't say that a yield statement is necessary
for making a generator function. In other words, it doesn't say that a
function that doesn't contain a yield statement isn't a generator
function.

The language reference is equally wishy-washy: "Using a yield statement
in a function definition is *sufficient* to cause that definition to
create a generator function instead of a normal function." [emphasis
mine]

Again, no indication that a yield statement is necessary for making a
generator function. It then proceeds to saying "When a generator
function is called, it returns an iterator known as a generator
iterator, or more commonly, a generator." That condition seems to be
true for the OP's frange() function, even though it doesn't have a yield
statement.

Until somebody can point out a definition that says unequivocally "an
object is a generator function if and only if ...", it's up in the air
whether frange() is a generator function or merely impersonates a
generator function. Ultimately, though, this is a purely academic
question without a useful answer. The useful conclusion is that a
function can behave like a generator function without a yield statement,
and we have reached that conclusion a long time ago.

--
Carsten Haese
http://informixdb.sourceforge.net

```