Skip to content

Instantly share code, notes, and snippets.

@mikhail
Last active June 13, 2019 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikhail/bc141339486ac2e8143a to your computer and use it in GitHub Desktop.
Save mikhail/bc141339486ac2e8143a to your computer and use it in GitHub Desktop.
Python Generators and Yielding

Python Generators and Yielding

In python yield can be used to transfer information in both directions.

yield 'hello'

will generate (vs return) the string "hello", whereas

x = yield

will receive a value from .send() method.

The output of the example blow will be:

$ python yield_example.py
0
1
2
Exiting out of here
def number_generator():
x = 0
while True:
abort = yield x # Generate x AND see if anything was sent!
if abort:
break
else:
x = x + 1
yield 'Exiting out of here'
ng = number_generator()
print ng.next()
print ng.next()
print ng.next()
print ng.send(True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment