Skip to content

Instantly share code, notes, and snippets.

Created August 10, 2016 06:37
Show Gist options
  • Save anonymous/13196290402f7f84b588c5834ac03775 to your computer and use it in GitHub Desktop.
Save anonymous/13196290402f7f84b588c5834ac03775 to your computer and use it in GitHub Desktop.
Why Python's 3.x's "yield from" is useful
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Why 'yield from' is Useful"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lets say you have a generator, `foo()`, that needs to present data from a another generator, `bar()`. One might naively yield the sub-generator:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def foo():\n",
" yield 1\n",
" yield 2\n",
" yield bar()\n",
"\n",
"def bar():\n",
" yield 3\n",
" yield 4"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, <generator object bar at 0x7fc29017eaf8>]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(foo())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Oh no! There's a generator in my list"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"# Enter 'yield from'"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4]"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def foo():\n",
" yield 1\n",
" yield 2\n",
" yield from bar()\n",
"\n",
"def bar():\n",
" yield 3\n",
" yield 4\n",
" \n",
"list(foo())"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"Much better"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# In a World Without 'yield from' (Python 2.7)\n",
"\n",
"To get the same behavior without yield from you must delegate iteration to the parent generator"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4]"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def foo():\n",
" yield 1\n",
" yield 2\n",
" for elem in bar():\n",
" yield elem\n",
"\n",
"def bar():\n",
" yield 3\n",
" yield 4\n",
" \n",
"list(foo())"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.5"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment