In python is there a way to check if a function is a “generator function” before calling it?

后端 未结 3 1235
日久生厌
日久生厌 2020-12-13 03:44

Lets say I have two functions:

def foo():
  return \'foo\'

def bar():
  yield \'bar\'

The first one is a normal function, and the second i

3条回答
  •  鱼传尺愫
    2020-12-13 03:53

    >>> import inspect
    >>> 
    >>> def foo():
    ...   return 'foo'
    ... 
    >>> def bar():
    ...   yield 'bar'
    ... 
    >>> print inspect.isgeneratorfunction(foo)
    False
    >>> print inspect.isgeneratorfunction(bar)
    True
    
    • New in Python version 2.6

提交回复
热议问题