Search code examples
pythongenerator

Difference between generators and functions returning generators


I was debugging some code with generators and came to this question. Assume I have a generator function

def f(x):
    yield x

and a function returning a generator:

def g(x):
    return f(x)

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 inspect)?


Solution

  • They will act the same. And about way to distinguish the two (without inspect). In python? Only inspect:

    import inspect
    
    print inspect.isgeneratorfunction(g) --> False
    print inspect.isgeneratorfunction(f) --> True
    

    Of course you can also check it using dis:

    Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def f(x):
    ...     yield x
    ... 
    >>> def g(x):
    ...     return f(x)
    ... 
    >>> import dis
    >>> dis.dis(f)
      2           0 LOAD_FAST                0 (x)
                  3 YIELD_VALUE         
                  4 POP_TOP             
                  5 LOAD_CONST               0 (None)
                  8 RETURN_VALUE        
    >>> dis.dis(g)
      2           0 LOAD_GLOBAL              0 (f)
                  3 LOAD_FAST                0 (x)
                  6 CALL_FUNCTION            1
                  9 RETURN_VALUE  
    

    but inspect is more appropriate.