Skip to content

Latest commit

 

History

History
32 lines (28 loc) · 889 Bytes

27_be_careful_with_yield.md

File metadata and controls

32 lines (28 loc) · 889 Bytes

def natural_numbers(): ... i = 0 ... while True: ... yield i ... i = i + 1 ... natural_numbers() # doctest: +ELLIPSIS <generator object natural_numbers at 0x...>

The following code cannot be run as a doctest since it will overwhelm the process. But it is the real output of a python REPL:

>>> list(natural_numbers())

^C^Z

[1]+ Stopped python

More code which can't be run:

def generate_once(): ... yield 1 ... generate_once() # doctest: +ELLIPSIS <generator object generate_once at 0x...> import sys sys.exit() for x in generate_once() Traceback (most recent call last): ... SyntaxError: invalid syntax (sys.exit() for x in generate_once()) # doctest: +ELLIPSIS <generator object at 0x...> foo = (sys.exit() for x in generate_once())

This line will exit python:

>>> list(foo)