Re: need help on need help on generator...

From: Terry Reedy (tjreedy_at_udel.edu)
Date: 01/23/05


To: python-list@python.org
Date: Sat, 22 Jan 2005 18:36:12 -0500


"Francis Girard" <francis.girard@free.fr> wrote in message
news:200501221106.49241.francis.girard@free.fr...

>If I understand correctly,

Almost...

> a "generator" produce something over which you can
> iterate with the help of an "iterator".

To be exact, the producer is a generator function, a function whose body
contains 'yield'. In CPython, the difference after executing the def is
that a generator function has a particular flag set. People sometimes
shorten 'generator function' to 'generator' as you did, but calling both a
factory and its products by the same name is confusing. (For instance, try
calling an automobile factory an automobile).

>>> def genf(): yield 1
...
>>> genf
<function genf at 0x008873B8>

The result of calling a generator function is a generator, which is one but
only one type of iterator.

>>> gen = genf()
>>> gen
<generator object at 0x008781F8>
>>> dir(gen)
[<stuff inherited from object>, '__iter__', ' gi_frame', 'gi_running',
'next']

The .__iter__ and .next methods make this an iterator. The two data
attributes are for internal use.

> Can you iterate (in the strict sense
>of an "iterator") over something not generated by a "generator" ?

Of course. Again, a generator is one specific type of iterator, where an
iterator is anything with the appropriate .__iter__ and .next methods.

Terry J. Reedy



Relevant Pages

  • Re: What makes an iterator an iterator?
    ... |> by improperly writing .next as a generator function ... | What iterator rule states that .next can't be a generator function? ... def f: ...
    (comp.lang.python)
  • Re: What makes an iterator an iterator?
    ... be a generator function. ... words = "Norwegian Blues have beautiful plumage!".split ... One can also make an iterable an iterator by correctly writing the ...
    (comp.lang.python)
  • Re: Problem When Unit Testing with PMock
    ... This was meant to be a generator function. ... yield None as the first line in the function has same effect. ... was/is that an iterator comsumer should be tested with an empty iterator. ... I am not familiar with pmock, but my impression is that mock objects are ...
    (comp.lang.python)
  • Re: generator functions in another language
    ... A 'generator function' -- a function that when called returns a generator ... object, a specific type of iterator, is a rather Python specific concept. ... I'll try to use Python code as an example. ... temp = self.a + self.b ...
    (comp.lang.python)
  • Re: Efficiently test for positive re.match then use the result?
    ... you might want to define a generator function: ... def reMatches (iterator, patternString): ...
    (comp.lang.python)