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>The best way to check it out is using <a href="https://docs.python.org/2/library/inspect.html#inspect.isgeneratorfunction" rel="nofollow">inspect.isgeneratorfunction</a>, which is quite simple function:</p>

<pre><code>def ismethod(object):
    """Return true if the object is an instance method.

    Instance method objects provide these attributes:
        __doc__         documentation string
        __name__        name with which this method was defined
        im_class        class object in which this method belongs
        im_func         function object containing implementation of method
        im_self         instance to which this method is bound, or None"""
    return isinstance(object, types.MethodType)

def isfunction(object):
    """Return true if the object is a user-defined function.

    Function objects provide these attributes:
        __doc__         documentation string
        __name__        name with which this function was defined
        func_code       code object containing compiled function bytecode
        func_defaults   tuple of any default values for arguments
        func_doc        (same as __doc__)
        func_globals    global namespace in which this function was defined
        func_name       (same as __name__)"""
    return isinstance(object, types.FunctionType)

def isgeneratorfunction(object):
    """Return true if the object is a user-defined generator function.

    Generator function objects provides same attributes as functions.

    See help(isfunction) for attributes listing."""
    return bool((isfunction(object) or ismethod(object)) and
                object.func_code.co_flags &amp; CO_GENERATOR)
</code></pre>

<p>Now, if you declared your generator using a syntax like this:</p>

<pre><code>my_generator = (i*i for i in range(1000000))
</code></pre>

<p>In that case, you could check its type quite easily, for instance, <code>__class__</code> will return <code>&lt;type 'generator'&gt;</code>.</p>

python generator