在Python中有一种方法来检查函数是否是“生成器函数”在打电话之前? [英] In python is there a way to check if a function is a "generator function" before calling it?
问题描述
可以说我有两个函数:
pre $ def foo():
return'foo'
def bar():
yield'bar'
第一个是一个正常的功能,第二个是发电机功能。现在我想写这样的内容:
def run(func):
if_generator_function(func):
gen = func()
gen.next()
#...运行生成器...
else:
func()
is_generator_function()
的直接实现是什么样的?使用类型
包可以测试 gen
是否是一个生成器,但是我希望在调用 FUNC()
。
现在考虑以下情况:
def goo():
if False:
yield
else:
return
调用 goo()
将返回一个生成器。我认为Python解析器知道 goo()
函数有一个yield语句,我不知道是否可以轻松获取这些信息。
谢谢!
>>>导入检查
>>>
>>> def foo():
... return'foo'
...
>>> def bar():
... yield'bar'
...
>>> print inspect.isgeneratorfunction(foo)
False
>>> print inspect.isgeneratorfunction(bar)
True
- Python版本2.6
Lets say I have two functions:
def foo():
return 'foo'
def bar():
yield 'bar'
The first one is a normal function, and the second is a generator function. Now I want to write something like this:
def run(func):
if is_generator_function(func):
gen = func()
gen.next()
#... run the generator ...
else:
func()
What will a straightforward implementation of is_generator_function()
look like? Using the types
package I can test if gen
is a generator, but I wish to do so before invoking func()
.
Now consider the following case:
def goo():
if False:
yield
else:
return
An invocation of goo()
will return a generator. I presume that the python parser knows that the goo()
function has a yield statement, and I wonder if it possible to get that information easily.
Thanks!
>>> 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
这篇关于在Python中有一种方法来检查函数是否是“生成器函数”在打电话之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!