Difference between generators and functions returning generators
<p>I was debugging some code with generators and came to this question. Assume I have a generator function</p>

<pre><code>def f(x):
    yield x
</code></pre>

<p>and a function returning a generator:</p>

<pre><code>def g(x):
    return f(x)
</code></pre>

<p>They surely return the same thing. Can there be any differences when using them interchangeably in Python code? Is there any way to distinguish the two (without <code>inspect</code>)?</p>

<p>If you want to <strong>identify</strong> what is a generator, the answer is simple.  <code>f</code> is a generator because it contains the  <code>yield</code> statement.  <code>g</code> is not a generator because it does not contain the <code>yield</code> statement. (You can have a look at <a href="https://docs.python.org/2/reference/simple_stmts.html?highlight=yield#the-yield-statement" rel="nofollow">https://docs.python.org/2/reference/simple_stmts.html?highlight=yield#the-yield-statement</a>)</p>

<p>As for what is the difference in <strong>using</strong> them, they are quite the same.  You can store a generator in a variable, then use it in a <code>for</code> statement.  In that case, <code>g(x)</code> just acts as a "middle man".  Have a look at the following examples:</p>

<pre><code>def f(x):
  for r in range(x):
    yield r

def g(x):
  return f(x)

print "using f(x)"
for i in f(3):
  print i

print "using g(x)"
for j in g(3):
  print j

print "store the iterator f(x) in a variable, then use it in a 'for' statement"
m = f(3)
for k in m:
  print k

print "store the iterator f(x) returned by g(x), then use it in a 'for' statement"
n = g(3)
for k in n:
  print k
</code></pre>

<p>These are in python2. Just add parentheses in print statements for python3.  </p>

python generator