且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

生成器和函数返回生成器之间的区别

更新时间:2021-07-12 08:57:57

它们的行为相同。以及如何区分这两者(没有inspect)。用蟒蛇吗?仅检查:

import inspect

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

当然也可以使用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  

inspect更合适。