Created
September 9, 2016 12:24
-
-
Save bofm/4785194ba9de91c5a2a59cc3b153fd1c to your computer and use it in GitHub Desktop.
Lazy stats
This file contains hidden or 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": 121, | |
| "metadata": { | |
| "collapsed": false | |
| }, | |
| "outputs": [ | |
| { | |
| "name": "stdout", | |
| "output_type": "stream", | |
| "text": [ | |
| "0\n", | |
| "1\n", | |
| "2\n", | |
| "3\n", | |
| "4\n", | |
| "5\n", | |
| "6\n", | |
| "7\n", | |
| "8\n", | |
| "9\n" | |
| ] | |
| }, | |
| { | |
| "data": { | |
| "text/plain": [ | |
| "{'sum': 45}" | |
| ] | |
| }, | |
| "execution_count": 121, | |
| "metadata": {}, | |
| "output_type": "execute_result" | |
| } | |
| ], | |
| "source": [ | |
| "class Stats:\n", | |
| " def __init__(self):\n", | |
| " self.processors = {}\n", | |
| " \n", | |
| " def __call__(self, name):\n", | |
| " def wrapper(fn):\n", | |
| " self.processors[name] = fn\n", | |
| " return fn\n", | |
| " return wrapper\n", | |
| "\n", | |
| " def run(self, iterable):\n", | |
| " running = {}\n", | |
| " \n", | |
| " for fn in self.processors.values():\n", | |
| " running[fn] = gen = fn()\n", | |
| " gen.send(None)\n", | |
| " \n", | |
| " for x in iterable:\n", | |
| " for gen in running.values():\n", | |
| " gen.send(x)\n", | |
| " \n", | |
| " results = {}\n", | |
| " for name, fn in self.processors.items():\n", | |
| " try:\n", | |
| " running[fn].throw(StopIteration)\n", | |
| " except StopIteration as e:\n", | |
| " res = e.value\n", | |
| " results[name] = res\n", | |
| " return results\n", | |
| " \n", | |
| "stats = Stats() \n", | |
| " \n", | |
| "\n", | |
| "@stats('sum')\n", | |
| "def sumer():\n", | |
| " res = 0\n", | |
| " try: \n", | |
| " while True:\n", | |
| " x = yield\n", | |
| " res += x\n", | |
| " print(x)\n", | |
| " finally:\n", | |
| " return res\n", | |
| " \n", | |
| "\n", | |
| "\n", | |
| "stats.run(range(10))" | |
| ] | |
| } | |
| ], | |
| "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.5.2" | |
| } | |
| }, | |
| "nbformat": 4, | |
| "nbformat_minor": 0 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment