Python返回空迭代器(停止迭代器)

分类: python

2020-12-26

|

1908

|

评论:0

分享:

在Python中返回一个空迭代器(停止迭代器)有三种方法:

def empty():
    return
    yield
def empty():
    return iter(())

Python3.3+ 可以用:

def empty():
    yield from ()

推荐优先使用 return yield 的方法,因为这种方法编译后的字节码最少

In [1]: import dis

In [2]: def empty_yield_from():
   ...:     yield from ()
   ...: 

In [3]: def empty_iter():
   ...:     return iter(())
   ...: 

In [4]: def empty_return():
   ...:     return
   ...:     yield
   ...: 

In [5]: dis.dis(empty_yield_from)
  2           0 LOAD_CONST               1 (())
              2 GET_YIELD_FROM_ITER
              4 LOAD_CONST               0 (None)
              6 YIELD_FROM
              8 POP_TOP
             10 LOAD_CONST               0 (None)
             12 RETURN_VALUE

In [6]: dis.dis(empty_iter)
  2           0 LOAD_GLOBAL              0 (iter)
              2 LOAD_CONST               1 (())
              4 CALL_FUNCTION            1
              6 RETURN_VALUE

In [7]: dis.dis(empty_return)
  2           0 LOAD_CONST               0 (None)
              2 RETURN_VALUE

如果使用类,可以通过抛出 StopIteration 异常来实现,如:

class EmptyGenerator:
    def __iter__(self):
        return self
    def __next__(self):
        raise StopIteration

Powered by Froala Editor



转载请注明来源

文章:Python返回空迭代器(停止迭代器)

链接:/article/59

作者:gojuukaze

标签: python yield
本文共 0 个回复

发表评论 (对文章评论)

captcha