*Memo:
- My post explains a generator (1).
- My post explains a generator (3).
- My post explains a generator (4).
A generator comprehension can create a generator's iterator as shown below:
v = (x**2 for x in [0, 1, 2, 3, 4, 5, 6, 7]) print(v) # <generator object <genexpr> at 0x0000020E06F9F6B0> print(type(v)) # <class 'generator'> for x in v: print(x) # 0 # 1 # 4 # 9 # 16 # 25 # 36 # 49 A generator's iterator cannot be copied as shown below:
import copy def gen(): yield 0 yield 1 yield 2 # yield from [0, 1, 2] v1 = gen() v2 = copy.copy(v1) v2 = copy.deepcopy(v1) # TypeError: cannot pickle 'generator' object throw() can raise an exception at the point where the generator is paused as shown below:
*Memo:
- The 1st argument is
value(Required-Type:BaseException):- Don't use value=.
<yield without a try statement>:
def gen(): yield 0 yield 1 yield 2 yield 3 v = gen() print(next(v)) # 0 print(next(v)) # 1 print(v.throw(Exception)) # Exception: <yield from without a try statement>:
def gen(): yield from [0, 1, 2, 3] v = gen() print(next(v)) # 0 print(next(v)) # 1 print(v.throw(Exception)) # Exception: <yield with a try statement>:
def gen(): yield 0 try: yield 1 except Exception: pass yield 2 yield 3 v = gen() print(next(v)) # 0 print(next(v)) # 1 print(v.throw(Exception)) # 2 print(next(v)) # 3 <yield from with a try statement>:
def gen(): try: yield from [0, 1] except Exception: pass yield from [2, 3] v = gen() print(next(v)) # 0 print(next(v)) # 1 print(v.throw(Exception)) # 2 print(next(v)) # 3 close() can terminate a generator as shown below:
*Memo:
- It has no arguments.
- It should be used in a
finallyclause to terminate a generator for if error occurs.
<yield without a finally clause>:
def gen(): yield 0 yield 1 yield 2 yield 3 v = gen() print(next(v)) # 0 print(next(v)) # 1 v.close() print(next(v)) # StopIteration: <yield with a finally clause>:
def gen(): yield 0 yield 1 yield 2 yield 3 v = gen() try: print(next(v)) # 0 print(next(v)) # 1 print(next(v)) # 2 print(next(v)) # 3 finally: v.close() <yield from without a finally clause>:
def gen(): yield from [0, 1, 2, 3] v = gen() print(next(v)) # 0 print(next(v)) # 1 v.close() print(next(v)) # StopIteration: <yield from with a finally clause>:
def gen(): yield from [0, 1, 2, 3] v = gen() try: print(next(v)) # 0 print(next(v)) # 1 print(next(v)) # 2 print(next(v)) # 3 finally: v.close()
Top comments (0)