{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n", "#\n", "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# http://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License.\n", "\n", "# Preamble to mimick book environment\n", "import logging\n", "from pprint import pprint\n", "from sys import stdout as STDOUT" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Plato', 'Socrates', 'Aristotle', 'Archimedes']\n" ] } ], "source": [ "# Example 1\n", "names = ['Socrates', 'Archimedes', 'Plato', 'Aristotle']\n", "names.sort(key=lambda x: len(x))\n", "print(names)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Example 2\n", "from collections import defaultdict\n", "\n", "def log_missing():\n", " print('Key added')\n", " return 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### We can pass function as an argument " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before: {'green': 12, 'blue': 3}\n", "Key added\n", "Key added\n", "After: {'red': 5, 'orange': 9, 'green': 12, 'blue': 20}\n" ] } ], "source": [ "# Example 3\n", "current = {'green': 12, 'blue': 3}\n", "increments = [\n", " ('red', 5),\n", " ('blue', 17),\n", " ('orange', 9),\n", "]\n", "result = defaultdict(log_missing, current)\n", "print('Before:', dict(result))\n", "for key, amount in increments:\n", " result[key] += amount\n", "print('After: ', dict(result))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Example 4\n", "def increment_with_report(current, increments):\n", " added_count = 0\n", "\n", " def missing():\n", " nonlocal added_count # Stateful closure\n", " added_count += 1\n", " return 0\n", "\n", " result = defaultdict(missing, current)\n", " for key, amount in increments:\n", " result[key] += amount\n", "\n", " return result, added_count" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "defaultdict(.missing at 0x103e7dd08>, {'red': 5, 'orange': 9, 'green': 12, 'blue': 20})\n" ] } ], "source": [ "# Example 5\n", "result, count = increment_with_report(current, increments)\n", "assert count == 2\n", "print(result)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Example 6\n", "class CountMissing(object):\n", " def __init__(self):\n", " self.added = 0\n", "\n", " def missing(self):\n", " self.added += 1\n", " return 0" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "defaultdict(>, {'red': 5, 'orange': 9, 'green': 12, 'blue': 20})\n" ] } ], "source": [ "# Example 7\n", "counter = CountMissing()\n", "result = defaultdict(counter.missing, current) # Method reference\n", "for key, amount in increments:\n", " result[key] += amount\n", "assert counter.added == 2\n", "print(result)\n", "\n", "\n", "# Example 8\n", "class BetterCountMissing(object):\n", " def __init__(self):\n", " self.added = 0\n", "\n", " def __call__(self):\n", " self.added += 1\n", " return 0\n", "\n", "counter = BetterCountMissing()\n", "counter()\n", "assert callable(counter)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "defaultdict(<__main__.BetterCountMissing object at 0x103e8ca58>, {'red': 5, 'orange': 9, 'green': 12, 'blue': 20})\n" ] } ], "source": [ "# Example 9\n", "counter = BetterCountMissing()\n", "result = defaultdict(counter, current) # Relies on __call__\n", "for key, amount in increments:\n", " result[key] += amount\n", "assert counter.added == 2\n", "print(result)" ] } ], "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.1" } }, "nbformat": 4, "nbformat_minor": 0 }