Skip to content

Instantly share code, notes, and snippets.

@travishen
Created August 26, 2019 15:39
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 travishen/0d91ce5425acb8c553db3da1650e7b64 to your computer and use it in GitHub Desktop.
Save travishen/0d91ce5425acb8c553db3da1650e7b64 to your computer and use it in GitHub Desktop.
capture values return from sub generator
Display the source blob
Display the rendered blob
Raw
{
"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