Do generators simply make new objects with __iter__ and next functions?
<p>I tried to search for this answer on my own, but there was too much noise.</p>

<p>Are generators in python just a convenience wrapper for the user to make an iterator object?</p>

<p>When you define the generator:</p>

<pre><code>def test():
  x = 0
  while True:
    x += 1
    yield x
</code></pre>

<p>is python simply making a new object, adding the <code>__iter__</code> method, then putting the rest of the code into the <code>next</code> function?</p>

<pre><code>class Test(object):

  def __init__(self):
    self.x = 0

  def __iter__(self):
    return self

  def next(self):
    self.x += 1
    return self.x
</code></pre>

<blockquote>
  <p>Are generators in python just a convenience wrapper for the user to make an iterator object?</p>
</blockquote>

<p>No. A <code>generator</code> is a function, where as <code>iterators</code> are class. Hence, generator can not be a object of iterator. But in some way you can say that <em>generator is a simplified approach to get iterator like capability</em>. It means:</p>

<blockquote>
  <p>All Generators are iterators, but not all iterators are generators.</p>
</blockquote>

<p>I will strongly suggest you refer below wiki links:</p>

<ul>
<li><a href="https://en.wikipedia.org/wiki/Iterator" rel="nofollow">Iterator</a> - traverses a collection one at a time</li>
<li><a href="https://en.wikipedia.org/wiki/Generator_(computer_programming)" rel="nofollow">Generator</a> - generates a sequence, one item at a time</li>
</ul>

<p>An iterator is typically something that has a <code>next</code> method to get the next element from a stream. A generator is an iterator that is tied to a function.</p>

<p>I will suggest you to refer: <a href="http://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators">Difference between Python's Generators and Iterators</a>.</p>

python