Created
August 26, 2019 15:39
-
-
Save travishen/0d91ce5425acb8c553db3da1650e7b64 to your computer and use it in GitHub Desktop.
capture values return from sub generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"def subgen():\n", | |
" try:\n", | |
" yield 10\n", | |
" yield 100\n", | |
" finally:\n", | |
" print('subgen closing...')\n", | |
" return 1000\n", | |
" \n", | |
"def delegator():\n", | |
" result = yield from subgen()\n", | |
" print('subgen returned: ', result)\n", | |
" yield 'delegator suspended'\n", | |
" print('delegator closing')\n", | |
" return 10000" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"10\n", | |
"100\n", | |
"subgen closing...\n", | |
"subgen returned: 1000\n", | |
"delegator suspended\n", | |
"delegator closing\n", | |
"delegator returned: 10000\n" | |
] | |
} | |
], | |
"source": [ | |
"d = delegator()\n", | |
"\n", | |
"while True:\n", | |
" try:\n", | |
" print(next(d))\n", | |
" except StopIteration as e:\n", | |
" print('delegator returned: ', e.value)\n", | |
" break" | |
] | |
} | |
], | |
"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.6.8" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment