├── LICENSE ├── README.md └── decorators-tutorial.ipynb /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **Disclaimer: This is not an official Google product.** 2 | 3 | A tutorial on decorators that I initially wrote for my team, and expanded into 4 | a more comprehensive resource. 5 | 6 | I do not currently plan to accept contributions until I have filled out the 7 | tutorial to my satisfaction. 8 | 9 | Written with help from Kevin Peterson. 10 | 11 | -------------------------------------------------------------------------------- /decorators-tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "Copyright 2016 Google Inc. All Rights Reserved.\n", 8 | "\n", 9 | "Licensed under the Apache License, Version 2.0 (the \"License\");\n", 10 | "you may not use this file except in compliance with the License.\n", 11 | "You may obtain a copy of the License at\n", 12 | "\n", 13 | " http://www.apache.org/licenses/LICENSE-2.0\n", 14 | "\n", 15 | "Unless required by applicable law or agreed to in writing, software\n", 16 | "distributed under the License is distributed on an \"AS IS\" BASIS,\n", 17 | "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", 18 | "See the License for the specific language governing permissions and\n", 19 | "limitations under the License." 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "

Table of Contents

\n", 27 | "
" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 1, 33 | "metadata": { 34 | "collapsed": false 35 | }, 36 | "outputs": [ 37 | { 38 | "data": { 39 | "application/javascript": [ 40 | "// From https://github.com/kmahelona/ipython_notebook_goodies\n", 41 | "$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')" 42 | ], 43 | "text/plain": [ 44 | "" 45 | ] 46 | }, 47 | "metadata": {}, 48 | "output_type": "display_data" 49 | } 50 | ], 51 | "source": [ 52 | "%%javascript\n", 53 | "// From https://github.com/kmahelona/ipython_notebook_goodies\n", 54 | "$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "# Basics" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": {}, 67 | "source": [ 68 | "There's lots of guides out there on decorators ([this](http://thecodeship.com/patterns/guide-to-python-function-decorators/) one is good), but I was never really sure when I would need to use decorators. Hopefully this will help motivate them a little more. Here I hope to show you:\n", 69 | "\n", 70 | "* When decorators might come in handy\n", 71 | "* How to write one\n", 72 | "* How to generalize using `*args` and `**kwargs` sorcery. \n", 73 | "\n", 74 | "You should read this if:\n", 75 | "\n", 76 | "* You've heard of decorators and want to know more about them, and/or\n", 77 | "* You want to know what `*args` and `**kwargs` mean.\n", 78 | "\n", 79 | "If you're here just for `*args` and `**kwargs`, start reading [here](#args)." 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "## Motivation\n", 87 | "\n", 88 | "Let's say you're defining methods on numbers:" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": 2, 94 | "metadata": { 95 | "collapsed": true 96 | }, 97 | "outputs": [], 98 | "source": [ 99 | "def add(n1, n2):\n", 100 | " return n1 + n2\n", 101 | "\n", 102 | "def multiply(n1, n2):\n", 103 | " return n1 * n2\n", 104 | "\n", 105 | "def exponentiate(n1, n2):\n", 106 | " \"\"\"Raise n1 to the power of n2\"\"\"\n", 107 | " import math\n", 108 | " return math.pow(n1, n2)" 109 | ] 110 | }, 111 | { 112 | "cell_type": "markdown", 113 | "metadata": {}, 114 | "source": [ 115 | "Well, we only want these functions to work if both inputs are numbers. So we could do:" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": 3, 121 | "metadata": { 122 | "collapsed": true 123 | }, 124 | "outputs": [], 125 | "source": [ 126 | "def is_number(n):\n", 127 | " \"\"\"Return True iff n is a number.\"\"\"\n", 128 | " # A number can always be converted to a float\n", 129 | " try:\n", 130 | " float(n)\n", 131 | " return True\n", 132 | " except ValueError:\n", 133 | " return False\n", 134 | " \n", 135 | "def add(n1, n2):\n", 136 | " if not (is_number(n1) and is_number(n2)):\n", 137 | " print(\"Arguments must be numbers!\")\n", 138 | " return\n", 139 | " return n1 + n2\n", 140 | "\n", 141 | "def multiply(n1, n2):\n", 142 | " if not (is_number(n1) and is_number(n2)):\n", 143 | " print(\"Arguments must be numbers!\")\n", 144 | " return\n", 145 | " return n1 * n2\n", 146 | "\n", 147 | "def exponentiate(n1, n2):\n", 148 | " \"\"\"Raise n1 to the power of n2\"\"\"\n", 149 | " if not (is_number(n1) and is_number(n2)):\n", 150 | " print(\"Arguments must be numbers!\")\n", 151 | " return\n", 152 | " import math\n", 153 | " return math.pow(n1, n2)" 154 | ] 155 | }, 156 | { 157 | "cell_type": "markdown", 158 | "metadata": {}, 159 | "source": [ 160 | "But this is yucky: we had to copy and paste code. This should always make you sad! For example, what if you wanted to change the message slightly? Or to return an error instead? You'd have to change it everywhere it appears... \n", 161 | "\n", 162 | "We want the copy & pasted code to live in just one place, so any changes just go there (DRY code: Don't Repeat Yourself). So let's **refactor**. " 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": 4, 168 | "metadata": { 169 | "collapsed": true 170 | }, 171 | "outputs": [], 172 | "source": [ 173 | "def validate_two_arguments(n1, n2):\n", 174 | " \"\"\"\n", 175 | " Returns True if n1 and n2 are both numbers.\n", 176 | " \"\"\"\n", 177 | " if not (is_number(n1) and is_number(n2)):\n", 178 | " return False\n", 179 | " return True\n", 180 | "\n", 181 | "def add(n1, n2):\n", 182 | " if validate_two_arguments(n1, n2):\n", 183 | " return n1 + n2\n", 184 | "\n", 185 | "def multiply(n1, n2):\n", 186 | " if validate_two_arguments(n1, n2):\n", 187 | " return n1 * n2\n", 188 | "\n", 189 | "def exponentiate(n1, n2):\n", 190 | " \"\"\"Raise n1 to the power of n2\"\"\"\n", 191 | " if validate_two_arguments(n1, n2):\n", 192 | " import math\n", 193 | " return math.pow(n1, n2)" 194 | ] 195 | }, 196 | { 197 | "cell_type": "markdown", 198 | "metadata": {}, 199 | "source": [ 200 | "This is definitely better. But there's still some repeated logic. Like, what if we want to return an error if we don't get numbers, or print something before running the code? We'd still have to make the changes in multiple places. The code isn't DRY. " 201 | ] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "metadata": {}, 206 | "source": [ 207 | "## Basic decorators\n", 208 | "\n", 209 | "We can refactor further with the **decorator pattern**.\n", 210 | "\n", 211 | "We want to write something that looks like\n", 212 | " \n", 213 | " @decorator\n", 214 | " def add(n1, n2):\n", 215 | " return n1 + n2\n", 216 | "\n", 217 | "so that all the logic about validating `n1` and `n2` lives in one place, and the functions just do what we want them to do. \n", 218 | " \n", 219 | "Since the @ syntax just means `add = decorator(add)`, we know the decorator needs to take a function as an argument, and it needs to return a function. (This should be confusing at first. Functions returning functions are scary, but think about it until that doesn't seem outlandish to you.)\n", 220 | "\n", 221 | "This returned function should act the same way as `add`, so it should take two arguments. And within this returned function, we want to first check that the arguments are numbers. If they are, we want to call the original function that we decorated (in this case, `add`). If not, we don't want to do anything. Here's what that looks like (there's a lot here, so use the comments to understand what's happening):" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": 5, 227 | "metadata": { 228 | "collapsed": true 229 | }, 230 | "outputs": [], 231 | "source": [ 232 | "# The decorator: takes a function.\n", 233 | "def validate_arguments(func):\n", 234 | " # The decorator will be returning wrapped_func, a function that has the \n", 235 | " # same signature as add, multiply, etc.\n", 236 | " def wrapped_func(n1, n2):\n", 237 | " # If we don't have two numbers, we don't want to run the function. \n", 238 | " # Best practice (\"be explicit\") is to raise an error here \n", 239 | " # instead of just returning None.\n", 240 | " if not validate_two_arguments(n1, n2):\n", 241 | " raise Exception(\"Arguments must be numbers!\")\n", 242 | " # We've passed our checks, so we can call the function with the passed in arguments.\n", 243 | " # If you like, think of this as\n", 244 | " # result = func(n1, n2)\n", 245 | " # return result\n", 246 | " # to distinguish it from the outer return where we're returning a function.\n", 247 | " return func(n1, n2)\n", 248 | " # This is where we return the function that has the same signature.\n", 249 | " return wrapped_func" 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": 6, 255 | "metadata": { 256 | "collapsed": false 257 | }, 258 | "outputs": [ 259 | { 260 | "name": "stdout", 261 | "output_type": "stream", 262 | "text": [ 263 | "4\n", 264 | "Caught Exception: Arguments must be numbers!\n" 265 | ] 266 | } 267 | ], 268 | "source": [ 269 | "@validate_arguments\n", 270 | "def add(n1, n2):\n", 271 | " return n1 + n2\n", 272 | "# Don't forget, the @ syntax just means\n", 273 | "# add = validate_decorator(add)\n", 274 | "\n", 275 | "print(add(1, 3))\n", 276 | "try:\n", 277 | " add(2, 'hi')\n", 278 | "except Exception as e:\n", 279 | " print(\"Caught Exception: {}\".format(e))" 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "metadata": {}, 285 | "source": [ 286 | "This pattern is nice because we've even refactored out all the validation logic (even the \"if blah then blah\" part) into the decorator. " 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": {}, 292 | "source": [ 293 | "## Generalizing with \\*args and \\**kwargs\n", 294 | "\n", 295 | "What if we want to validate a function that has a different number of arguments?" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": 7, 301 | "metadata": { 302 | "collapsed": false 303 | }, 304 | "outputs": [ 305 | { 306 | "ename": "TypeError", 307 | "evalue": "wrapped_func() takes exactly 2 arguments (3 given)", 308 | "output_type": "error", 309 | "traceback": [ 310 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 311 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 312 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mn1\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mn2\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mn3\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0madd3\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 313 | "\u001b[0;31mTypeError\u001b[0m: wrapped_func() takes exactly 2 arguments (3 given)" 314 | ] 315 | } 316 | ], 317 | "source": [ 318 | "@validate_arguments # Won't work!\n", 319 | "def add3(n1, n2, n3):\n", 320 | " return n1 + n2 + n3\n", 321 | "\n", 322 | "add3(1, 2, 3)" 323 | ] 324 | }, 325 | { 326 | "cell_type": "markdown", 327 | "metadata": {}, 328 | "source": [ 329 | "We can't decorate this because the wrapped function expects 2 arguments. \n", 330 | "\n", 331 | "Here's where we use the `*` symbol. I'll write out the code so you can see how it looks, and we'll look at what `*args` is doing below. " 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": 8, 337 | "metadata": { 338 | "collapsed": true 339 | }, 340 | "outputs": [], 341 | "source": [ 342 | "# The decorator: takes a function.\n", 343 | "def validate_arguments(func):\n", 344 | " # Note the *args! Think of this as representing \"as many arguments as you want\". \n", 345 | " # So this function will take an arbitrary number of arguments.\n", 346 | " def wrapped_func(*args):\n", 347 | " # We just want to apply the check to each argument.\n", 348 | " for arg in args:\n", 349 | " if not is_number(arg):\n", 350 | " raise Exception(\"Arguments must be numbers!\")\n", 351 | " # We also want to make sure there's at least two arguments.\n", 352 | " if len(args) < 2:\n", 353 | " raise Exception(\"Must specify at least 2 arguments!\")\n", 354 | " \n", 355 | " # We've passed our checks, so we can call the function with the \n", 356 | " # passed-in arguments.\n", 357 | " # Right now, args is a tuple of all the different arguments passed in \n", 358 | " # (more explanation below), so we want to expand them back out when \n", 359 | " # calling the function.\n", 360 | " return func(*args)\n", 361 | " return wrapped_func" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": 9, 367 | "metadata": { 368 | "collapsed": false 369 | }, 370 | "outputs": [ 371 | { 372 | "data": { 373 | "text/plain": [ 374 | "6" 375 | ] 376 | }, 377 | "execution_count": 9, 378 | "metadata": {}, 379 | "output_type": "execute_result" 380 | } 381 | ], 382 | "source": [ 383 | "@validate_arguments # This works\n", 384 | "def add3(n1, n2, n3):\n", 385 | " return n1 + n2 + n3\n", 386 | "\n", 387 | "add3(1, 2, 3)" 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "execution_count": 10, 393 | "metadata": { 394 | "collapsed": false 395 | }, 396 | "outputs": [ 397 | { 398 | "name": "stdout", 399 | "output_type": "stream", 400 | "text": [ 401 | "15\n", 402 | "45\n" 403 | ] 404 | } 405 | ], 406 | "source": [ 407 | "@validate_arguments # And so does this\n", 408 | "def addn(*args):\n", 409 | " \"\"\"Add an arbitrary number of numbers together\"\"\"\n", 410 | " cumu = 0\n", 411 | " for arg in args:\n", 412 | " cumu += arg\n", 413 | " return cumu\n", 414 | "print(addn(1, 2, 3, 4, 5))\n", 415 | "# range(n) gives a list, so we expand the list into positional arguments...\n", 416 | "print(addn(*range(10)))" 417 | ] 418 | }, 419 | { 420 | "cell_type": "markdown", 421 | "metadata": {}, 422 | "source": [ 423 | "### `*args`\n", 424 | "What is this `*` nonsense?\n", 425 | "\n", 426 | "You've probably seen `*args` and `**kwargs` in documentation before. Here's what they mean:\n", 427 | "\n", 428 | "* When calling a function, `*` **expands an iterable** into **positional arguments**. \n", 429 | " * Terminology note: in a call like `bing(1, 'hi', name='fig')`, `1` is the first positional argument, `'hi'` is the second positional argument, and there's a keyword argument `'name'` with the value `'fig'`.\n", 430 | "* When defining a signature, `*args` represents an **arbitrary number of positional arguments**." 431 | ] 432 | }, 433 | { 434 | "cell_type": "code", 435 | "execution_count": 11, 436 | "metadata": { 437 | "collapsed": false 438 | }, 439 | "outputs": [ 440 | { 441 | "name": "stdout", 442 | "output_type": "stream", 443 | "text": [ 444 | "First call:\n", 445 | "foo args: (1, 2, 'a', 3, True)\n", 446 | "foo args type: \n", 447 | "\n", 448 | "Second call:\n", 449 | "foo args: (1, 2, 'a', 3, True)\n", 450 | "foo args type: \n" 451 | ] 452 | } 453 | ], 454 | "source": [ 455 | "def foo(*args):\n", 456 | " print(\"foo args: {}\".format(args))\n", 457 | " print(\"foo args type: {}\".format(type(args)))\n", 458 | " \n", 459 | "# So foo can take an arbitrary number of arguments\n", 460 | "print(\"First call:\")\n", 461 | "foo(1, 2, 'a', 3, True)\n", 462 | "\n", 463 | "# Which can be written using the * syntax to expand an iterable\n", 464 | "print(\"\\nSecond call:\")\n", 465 | "l = [1, 2, 'a', 3, True]\n", 466 | "foo(*l)" 467 | ] 468 | }, 469 | { 470 | "cell_type": "markdown", 471 | "metadata": {}, 472 | "source": [ 473 | "### Back to the decorator\n", 474 | "(If you're just here for \\*args and \\*\\*kwargs, skip down to [here](#kwargs))\n", 475 | "\n", 476 | "So let's look at the decorator code again, minus the comments:\n", 477 | "\n", 478 | " def validate_decorator(func):\n", 479 | " def wrapped_func(*args):\n", 480 | " for arg in args:\n", 481 | " if not is_number(arg):\n", 482 | " print(\"arguments must be numbers!\")\n", 483 | " return\n", 484 | " return func(*args)\n", 485 | " return wrapped_func\n", 486 | " \n", 487 | "* `def wrapped_func(*args)` says that `wrapped_func` can take an arbitrary number of arguments.\n", 488 | "* Within `wrapped_func`, we interact with `args` as a tuple containing all the (positional) arguments passed in. \n", 489 | "* If all the arguments are numbers, we call `func`, the function we decorated, by **expanding** the `args` tuple back out into positional arguments: `func(*args)`.\n", 490 | "* Finally the decorator needs to return a function (remember that the `@` syntax is just sugar for `add = decorator(add)`.\n", 491 | "\n", 492 | "Congrats, you now understand decorators! You can do tons of other stuff with them, but hopefully now you're equipped to read the other guides online. \n", 493 | "\n", 494 | "---\n", 495 | "\n", 496 | "### As for `**kwargs`: \n", 497 | "* When calling a function, `**` **expands a dict** into **keyword arguments**.\n", 498 | "* When defining a signature, `**kwargs` represents an **arbitrary number of keyword arguments**." 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": 12, 504 | "metadata": { 505 | "collapsed": false 506 | }, 507 | "outputs": [ 508 | { 509 | "name": "stdout", 510 | "output_type": "stream", 511 | "text": [ 512 | "First call:\n", 513 | "bar kwargs: {'age': None, 'location': 'US-PAO', 'ldap': 'awan'}\n", 514 | "\n", 515 | "Second call:\n", 516 | "bar kwargs: {'age': None, 'location': 'US-PAO', 'ldap': 'awan'}\n" 517 | ] 518 | } 519 | ], 520 | "source": [ 521 | "def bar(**kwargs):\n", 522 | " print(\"bar kwargs: {}\".format(kwargs))\n", 523 | "\n", 524 | "# bar takes an arbitrary number of keyword arguments\n", 525 | "print(\"First call:\")\n", 526 | "bar(location='US-PAO', ldap='awan', age=None)\n", 527 | "\n", 528 | "# Which can also be written using the ** syntax to expand a dict\n", 529 | "print(\"\\nSecond call:\")\n", 530 | "d = {'location': 'US-PAO', 'ldap': 'awan', 'age': None}\n", 531 | "bar(**d)" 532 | ] 533 | }, 534 | { 535 | "cell_type": "markdown", 536 | "metadata": {}, 537 | "source": [ 538 | "And in case your head doesn't hurt yet, we can do both together:" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": 13, 544 | "metadata": { 545 | "collapsed": false 546 | }, 547 | "outputs": [ 548 | { 549 | "name": "stdout", 550 | "output_type": "stream", 551 | "text": [ 552 | "First call:\n", 553 | "baz args: (1, 3, 'hi'). kwargs: {'age': 37, 'name': 'Joe', 'occupation': 'Engineer'}\n", 554 | "\n", 555 | "Second call:\n", 556 | "baz args: (1, 3, 'hi'). kwargs: {'age': 37, 'name': 'Joe', 'occupation': 'Engineer'}\n" 557 | ] 558 | } 559 | ], 560 | "source": [ 561 | "def baz(*args, **kwargs):\n", 562 | " print(\"baz args: {}. kwargs: {}\".format(args, kwargs))\n", 563 | " \n", 564 | "# Calling baz with a mixture of positional and keyword arguments\n", 565 | "print(\"First call:\")\n", 566 | "baz(1, 3, 'hi', name='Joe', age=37, occupation='Engineer')\n", 567 | "\n", 568 | "# Which is the same as\n", 569 | "print(\"\\nSecond call:\")\n", 570 | "l = [1, 3, 'hi']\n", 571 | "d = {'name': 'Joe', 'age': 37, 'occupation': 'Engineer'}\n", 572 | "baz(*l, **d)" 573 | ] 574 | }, 575 | { 576 | "cell_type": "markdown", 577 | "metadata": {}, 578 | "source": [ 579 | "---\n", 580 | "# Advanced decorators\n", 581 | "\n", 582 | "This section will introduce some of the many other useful ways you can use decorators. We'll talk about\n", 583 | "* Passing arguments into decorators\n", 584 | "* `functools.wraps`\n", 585 | "* Returning a different function\n", 586 | "* Decorators and objects.\n", 587 | "\n", 588 | "Use the [table of contents](#toc) at the top to make it easier to look around.\n", 589 | "\n", 590 | "## Decorators with arguments\n", 591 | "\n", 592 | "A common thing to want to do is to do some kind of configuration in a decorator. For example, let's say we want to define a `divide_n` method, and to make it easy to use we want to hide the existence of integer division. Let's define a decorator that converts arguments into floats." 593 | ] 594 | }, 595 | { 596 | "cell_type": "code", 597 | "execution_count": 14, 598 | "metadata": { 599 | "collapsed": false 600 | }, 601 | "outputs": [], 602 | "source": [ 603 | "def convert_arguments(func):\n", 604 | " \"\"\"\n", 605 | " Convert func arguments to floats.\n", 606 | " \"\"\"\n", 607 | " # Introducing the leading underscore: (weakly) marks a private \n", 608 | " # method/property that should not be accessed outside the defining\n", 609 | " # scope. Look up PEP 8 for more. \n", 610 | " def _wrapped_func(*args):\n", 611 | " new_args = [float(arg) for arg in args]\n", 612 | " return func(*new_args)\n", 613 | " return _wrapped_func\n", 614 | "\n", 615 | "@convert_arguments\n", 616 | "@validate_arguments\n", 617 | "def divide_n(*args):\n", 618 | " cumu = args[0]\n", 619 | " for arg in args[1:]:\n", 620 | " cumu = cumu / arg\n", 621 | " return cumu" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": 15, 627 | "metadata": { 628 | "collapsed": false 629 | }, 630 | "outputs": [ 631 | { 632 | "data": { 633 | "text/plain": [ 634 | "6.4375" 635 | ] 636 | }, 637 | "execution_count": 15, 638 | "metadata": {}, 639 | "output_type": "execute_result" 640 | } 641 | ], 642 | "source": [ 643 | "# The user doesn't need to think about integer division!\n", 644 | "divide_n(103, 2, 8)" 645 | ] 646 | }, 647 | { 648 | "cell_type": "markdown", 649 | "metadata": {}, 650 | "source": [ 651 | "But now let's say we want to define a `divide_n_as_integers` function. We could write a new decorator, or we could alter our decorator so that we can specify what we want to convert the arguments to. Let's try the latter. \n", 652 | "\n", 653 | "(For you smart alecks out there: yes you could use the `//` operator, but you'd still have to replicate the logic in `divide_n`. Nice try.)" 654 | ] 655 | }, 656 | { 657 | "cell_type": "code", 658 | "execution_count": 16, 659 | "metadata": { 660 | "collapsed": false 661 | }, 662 | "outputs": [ 663 | { 664 | "name": "stdout", 665 | "output_type": "stream", 666 | "text": [ 667 | "2.33333333333\n", 668 | "2\n" 669 | ] 670 | } 671 | ], 672 | "source": [ 673 | "def convert_arguments_to(to_type=float):\n", 674 | " \"\"\"\n", 675 | " Convert arguments to the given to_type by casting them.\n", 676 | " \"\"\"\n", 677 | " def _wrapper(func):\n", 678 | " def _wrapped_func(*args):\n", 679 | " new_args = [to_type(arg) for arg in args]\n", 680 | " return func(*new_args)\n", 681 | " return _wrapped_func\n", 682 | " return _wrapper\n", 683 | "\n", 684 | "\n", 685 | "@validate_arguments\n", 686 | "def divide_n(*args):\n", 687 | " cumu = args[0]\n", 688 | " for arg in args[1:]:\n", 689 | " cumu = cumu / arg\n", 690 | " return cumu\n", 691 | "\n", 692 | "\n", 693 | "@convert_arguments_to(to_type=int)\n", 694 | "def divide_n_as_integers(*args):\n", 695 | " return divide_n(*args)\n", 696 | "\n", 697 | "\n", 698 | "@convert_arguments_to(to_type=float)\n", 699 | "def divide_n_as_float(*args):\n", 700 | " return divide_n(*args)\n", 701 | "\n", 702 | "\n", 703 | "print(divide_n_as_float(7, 3))\n", 704 | "print(divide_n_as_integers(7, 3))" 705 | ] 706 | }, 707 | { 708 | "cell_type": "markdown", 709 | "metadata": {}, 710 | "source": [ 711 | "Did you notice the tricky thing about creating a decorator that takes arguments? **We had to create a function to \"return a decorator\".** The outermost function, `convert_arguments_to`, returns a function that takes a function, which is what we've been calling a \"decorator\". \n", 712 | "\n", 713 | "To think about why this is necessary, let's start from the form that we wanted to write, and unpack from there. We wanted to be able to do:\n", 714 | "\n", 715 | " @decorator(decorator_arg)\n", 716 | " def myfunc(*func_args):\n", 717 | " pass\n", 718 | " \n", 719 | "Unpacking the syntactic sugar gives us\n", 720 | "\n", 721 | " def myfunc(*func_args): \n", 722 | " pass\n", 723 | " myfunc = decorator(decorator_arg)(myfunc)\n", 724 | " \n", 725 | "Written this way, it should immediately be clear that `decorator(decorator_arg)` **returns a function that takes a function**. \n", 726 | "\n", 727 | "So that's how you write a decorator that takes an argument: it actually has to be a function that takes your decorator arguments, and returns a function that takes a function. " 728 | ] 729 | }, 730 | { 731 | "cell_type": "markdown", 732 | "metadata": {}, 733 | "source": [ 734 | "## functools.wraps\n", 735 | "If you've played around with the examples above, you might've seen that the name of the wrapped function changes after you apply a decorator... And perhaps more importantly, the docstring of the wrapped function changes too (this is important for when generating documentation, e.g. with Sphinx). " 736 | ] 737 | }, 738 | { 739 | "cell_type": "code", 740 | "execution_count": 17, 741 | "metadata": { 742 | "collapsed": false 743 | }, 744 | "outputs": [ 745 | { 746 | "name": "stdout", 747 | "output_type": "stream", 748 | "text": [ 749 | "wrapped_func\n", 750 | "None\n" 751 | ] 752 | } 753 | ], 754 | "source": [ 755 | "@validate_arguments\n", 756 | "def foo(*args):\n", 757 | " \"\"\"foo frobs bar\"\"\"\n", 758 | " pass\n", 759 | "\n", 760 | "\n", 761 | "print(foo.__name__)\n", 762 | "print(foo.__doc__)" 763 | ] 764 | }, 765 | { 766 | "cell_type": "markdown", 767 | "metadata": {}, 768 | "source": [ 769 | "[`functools.wraps`](https://docs.python.org/2/library/functools.html#functools.wraps) solves this problem. Use it as follows:" 770 | ] 771 | }, 772 | { 773 | "cell_type": "code", 774 | "execution_count": 18, 775 | "metadata": { 776 | "collapsed": false 777 | }, 778 | "outputs": [ 779 | { 780 | "name": "stdout", 781 | "output_type": "stream", 782 | "text": [ 783 | "bar\n", 784 | "bar frobs foo\n" 785 | ] 786 | } 787 | ], 788 | "source": [ 789 | "from functools import wraps\n", 790 | "\n", 791 | "def better_validate_arguments(func):\n", 792 | " @wraps(func)\n", 793 | " def wrapped_func(*args):\n", 794 | " for arg in args:\n", 795 | " if not is_number(arg):\n", 796 | " raise Exception(\"Arguments must be numbers!\")\n", 797 | " if len(args) < 2:\n", 798 | " raise Exception(\"Must specify at least 2 arguments!\")\n", 799 | " return func(*args)\n", 800 | " return wrapped_func\n", 801 | "\n", 802 | "\n", 803 | "@better_validate_arguments\n", 804 | "def bar(*args):\n", 805 | " \"\"\"bar frobs foo\"\"\"\n", 806 | " pass\n", 807 | "\n", 808 | "\n", 809 | "print(bar.__name__)\n", 810 | "print(bar.__doc__)" 811 | ] 812 | }, 813 | { 814 | "cell_type": "markdown", 815 | "metadata": {}, 816 | "source": [ 817 | "Think of the `@wraps` decorator making it so that `wrapped_func` knows what function it originally wrapped. " 818 | ] 819 | }, 820 | { 821 | "cell_type": "markdown", 822 | "metadata": {}, 823 | "source": [ 824 | "## Returning a different function\n", 825 | "\n", 826 | "Decorators don't even have to return the function that's passed in. You can have some fun with this..." 827 | ] 828 | }, 829 | { 830 | "cell_type": "code", 831 | "execution_count": 19, 832 | "metadata": { 833 | "collapsed": false 834 | }, 835 | "outputs": [ 836 | { 837 | "data": { 838 | "text/plain": [ 839 | "\"Not the droid you're looking for\"" 840 | ] 841 | }, 842 | "execution_count": 19, 843 | "metadata": {}, 844 | "output_type": "execute_result" 845 | } 846 | ], 847 | "source": [ 848 | "def jedi_mind_trick(func):\n", 849 | " def _jedi_func():\n", 850 | " return \"Not the droid you're looking for\"\n", 851 | " return _jedi_func\n", 852 | "\n", 853 | " \n", 854 | "@jedi_mind_trick\n", 855 | "def get_droid():\n", 856 | " return \"Found the droid!\"\n", 857 | "\n", 858 | "\n", 859 | "get_droid()" 860 | ] 861 | }, 862 | { 863 | "cell_type": "markdown", 864 | "metadata": {}, 865 | "source": [ 866 | "But more seriously, this can be useful for things like\n", 867 | "\n", 868 | "* Authentication: you don't want to return the function if the user isn't recognized, instead redirecting to a login page (e.g. you could check an environment variable)\n", 869 | "* Disabling test methods when deployed to a production environment\n", 870 | "\n", 871 | "This is also how `@unittest.skip` works, if you've ever used it to skip functions that weren't ready for testing or couldn't be tested on a particular operating system. " 872 | ] 873 | }, 874 | { 875 | "cell_type": "markdown", 876 | "metadata": {}, 877 | "source": [ 878 | "## Objects\n", 879 | "### Decorators that alter \"self\"\n", 880 | "### Decorating a class" 881 | ] 882 | } 883 | ], 884 | "metadata": { 885 | "kernelspec": { 886 | "display_name": "Python 2", 887 | "language": "python", 888 | "name": "python2" 889 | }, 890 | "language_info": { 891 | "codemirror_mode": { 892 | "name": "ipython", 893 | "version": 2 894 | }, 895 | "file_extension": ".py", 896 | "mimetype": "text/x-python", 897 | "name": "python", 898 | "nbconvert_exporter": "python", 899 | "pygments_lexer": "ipython2", 900 | "version": "2.7.8" 901 | } 902 | }, 903 | "nbformat": 4, 904 | "nbformat_minor": 0 905 | } 906 | --------------------------------------------------------------------------------