Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. _tut-morecontrol: |
| 2 | |
| 3 | *********************** |
| 4 | More Control Flow Tools |
| 5 | *********************** |
| 6 | |
Diego Alberto Barriga Martínez | b574813 | 2019-09-17 11:57:55 -0500 | [diff] [blame] | 7 | Besides the :keyword:`while` statement just introduced, Python uses the usual |
| 8 | flow control statements known from other languages, with some twists. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | |
| 10 | |
| 11 | .. _tut-if: |
| 12 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 13 | :keyword:`!if` Statements |
| 14 | ========================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 15 | |
| 16 | Perhaps the most well-known statement type is the :keyword:`if` statement. For |
| 17 | example:: |
| 18 | |
Georg Brandl | e9af284 | 2007-08-17 05:54:09 +0000 | [diff] [blame] | 19 | >>> x = int(input("Please enter an integer: ")) |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 20 | Please enter an integer: 42 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 21 | >>> if x < 0: |
Ezio Melotti | e65cb19 | 2013-11-17 22:07:48 +0200 | [diff] [blame] | 22 | ... x = 0 |
| 23 | ... print('Negative changed to zero') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 24 | ... elif x == 0: |
Ezio Melotti | e65cb19 | 2013-11-17 22:07:48 +0200 | [diff] [blame] | 25 | ... print('Zero') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | ... elif x == 1: |
Ezio Melotti | e65cb19 | 2013-11-17 22:07:48 +0200 | [diff] [blame] | 27 | ... print('Single') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 28 | ... else: |
Ezio Melotti | e65cb19 | 2013-11-17 22:07:48 +0200 | [diff] [blame] | 29 | ... print('More') |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 30 | ... |
| 31 | More |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 32 | |
| 33 | There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 34 | optional. The keyword ':keyword:`!elif`' is short for 'else if', and is useful |
| 35 | to avoid excessive indentation. An :keyword:`!if` ... :keyword:`!elif` ... |
| 36 | :keyword:`!elif` ... sequence is a substitute for the ``switch`` or |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 37 | ``case`` statements found in other languages. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 38 | |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 39 | If you're comparing the same value to several constants, or checking for specific types or |
| 40 | attributes, you may also find the :keyword:`!match` statement useful. For more |
| 41 | details see :ref:`tut-match`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 42 | |
| 43 | .. _tut-for: |
| 44 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 45 | :keyword:`!for` Statements |
| 46 | ========================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 47 | |
| 48 | .. index:: |
| 49 | statement: for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 50 | |
| 51 | The :keyword:`for` statement in Python differs a bit from what you may be used |
| 52 | to in C or Pascal. Rather than always iterating over an arithmetic progression |
| 53 | of numbers (like in Pascal), or giving the user the ability to define both the |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 54 | iteration step and halting condition (as C), Python's :keyword:`!for` statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 55 | iterates over the items of any sequence (a list or a string), in the order that |
| 56 | they appear in the sequence. For example (no pun intended): |
| 57 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 58 | .. One suggestion was to give a real C example here, but that may only serve to |
| 59 | confuse non-C programmers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 60 | |
| 61 | :: |
| 62 | |
| 63 | >>> # Measure some strings: |
Chris Jerdonek | 4fab8f0 | 2012-10-15 19:44:47 -0700 | [diff] [blame] | 64 | ... words = ['cat', 'window', 'defenestrate'] |
| 65 | >>> for w in words: |
| 66 | ... print(w, len(w)) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 67 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 68 | cat 3 |
| 69 | window 6 |
| 70 | defenestrate 12 |
| 71 | |
Raymond Hettinger | 6fcb6cf | 2019-08-22 23:44:19 -0700 | [diff] [blame] | 72 | Code that modifies a collection while iterating over that same collection can |
| 73 | be tricky to get right. Instead, it is usually more straight-forward to loop |
| 74 | over a copy of the collection or to create a new collection:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 75 | |
Antoine | 6fad3e6 | 2020-05-23 02:29:34 +0200 | [diff] [blame] | 76 | # Create a sample collection |
| 77 | users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'} |
| 78 | |
Raymond Hettinger | 6fcb6cf | 2019-08-22 23:44:19 -0700 | [diff] [blame] | 79 | # Strategy: Iterate over a copy |
| 80 | for user, status in users.copy().items(): |
| 81 | if status == 'inactive': |
| 82 | del users[user] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 83 | |
Raymond Hettinger | 6fcb6cf | 2019-08-22 23:44:19 -0700 | [diff] [blame] | 84 | # Strategy: Create a new collection |
| 85 | active_users = {} |
| 86 | for user, status in users.items(): |
| 87 | if status == 'active': |
| 88 | active_users[user] = status |
Georg Brandl | 40383c8 | 2016-02-15 17:50:33 +0100 | [diff] [blame] | 89 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 90 | |
| 91 | .. _tut-range: |
| 92 | |
| 93 | The :func:`range` Function |
| 94 | ========================== |
| 95 | |
| 96 | If you do need to iterate over a sequence of numbers, the built-in function |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 97 | :func:`range` comes in handy. It generates arithmetic progressions:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 98 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 99 | >>> for i in range(5): |
| 100 | ... print(i) |
| 101 | ... |
| 102 | 0 |
| 103 | 1 |
| 104 | 2 |
| 105 | 3 |
| 106 | 4 |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 107 | |
Georg Brandl | 7d82106 | 2010-06-27 10:59:19 +0000 | [diff] [blame] | 108 | The given end point is never part of the generated sequence; ``range(10)`` generates |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 109 | 10 values, the legal indices for items of a sequence of length 10. It |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 110 | is possible to let the range start at another number, or to specify a different |
| 111 | increment (even negative; sometimes this is called the 'step'):: |
| 112 | |
Miss Islington (bot) | aeb6339 | 2021-06-27 12:51:16 -0700 | [diff] [blame] | 113 | >>> list(range(5, 10)) |
| 114 | [5, 6, 7, 8, 9] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 115 | |
Miss Islington (bot) | aeb6339 | 2021-06-27 12:51:16 -0700 | [diff] [blame] | 116 | >>> list(range(0, 10, 3)) |
| 117 | [0, 3, 6, 9] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 118 | |
Miss Islington (bot) | aeb6339 | 2021-06-27 12:51:16 -0700 | [diff] [blame] | 119 | >>> list(range(-10, -100, -30)) |
| 120 | [-10, -40, -70] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 121 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 122 | To iterate over the indices of a sequence, you can combine :func:`range` and |
| 123 | :func:`len` as follows:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 124 | |
| 125 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
| 126 | >>> for i in range(len(a)): |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 127 | ... print(i, a[i]) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 128 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 129 | 0 Mary |
| 130 | 1 had |
| 131 | 2 a |
| 132 | 3 little |
| 133 | 4 lamb |
| 134 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 135 | In most such cases, however, it is convenient to use the :func:`enumerate` |
| 136 | function, see :ref:`tut-loopidioms`. |
| 137 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 138 | A strange thing happens if you just print a range:: |
| 139 | |
Miss Islington (bot) | aeb6339 | 2021-06-27 12:51:16 -0700 | [diff] [blame] | 140 | >>> range(10) |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 141 | range(0, 10) |
| 142 | |
| 143 | In many ways the object returned by :func:`range` behaves as if it is a list, |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 144 | but in fact it isn't. It is an object which returns the successive items of |
| 145 | the desired sequence when you iterate over it, but it doesn't really make |
| 146 | the list, thus saving space. |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 147 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 148 | We say such an object is :term:`iterable`, that is, suitable as a target for |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 149 | functions and constructs that expect something from which they can |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 150 | obtain successive items until the supply is exhausted. We have seen that |
Don Kirkby | 3ed4d25 | 2020-02-09 16:57:46 -0800 | [diff] [blame] | 151 | the :keyword:`for` statement is such a construct, while an example of a function |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 152 | that takes an iterable is :func:`sum`:: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 153 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 154 | >>> sum(range(4)) # 0 + 1 + 2 + 3 |
| 155 | 6 |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 156 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 157 | Later we will see more functions that return iterables and take iterables as |
Miss Islington (bot) | aeb6339 | 2021-06-27 12:51:16 -0700 | [diff] [blame] | 158 | arguments. In chapter :ref:`tut-structures`, we will discuss in more detail about |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 159 | :func:`list`. |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 160 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 161 | .. _tut-break: |
| 162 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 163 | :keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` Clauses on Loops |
| 164 | ============================================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 165 | |
regexaurus | 36fc896 | 2017-06-27 18:40:41 -0400 | [diff] [blame] | 166 | The :keyword:`break` statement, like in C, breaks out of the innermost enclosing |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 167 | :keyword:`for` or :keyword:`while` loop. |
| 168 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 169 | Loop statements may have an :keyword:`!else` clause; it is executed when the loop |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 170 | terminates through exhaustion of the iterable (with :keyword:`for`) or when the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 171 | condition becomes false (with :keyword:`while`), but not when the loop is |
| 172 | terminated by a :keyword:`break` statement. This is exemplified by the |
| 173 | following loop, which searches for prime numbers:: |
| 174 | |
| 175 | >>> for n in range(2, 10): |
| 176 | ... for x in range(2, n): |
| 177 | ... if n % x == 0: |
Georg Brandl | b03c1d9 | 2008-05-01 18:06:50 +0000 | [diff] [blame] | 178 | ... print(n, 'equals', x, '*', n//x) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 179 | ... break |
| 180 | ... else: |
| 181 | ... # loop fell through without finding a factor |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 182 | ... print(n, 'is a prime number') |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 183 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 184 | 2 is a prime number |
| 185 | 3 is a prime number |
| 186 | 4 equals 2 * 2 |
| 187 | 5 is a prime number |
| 188 | 6 equals 2 * 3 |
| 189 | 7 is a prime number |
| 190 | 8 equals 2 * 4 |
| 191 | 9 equals 3 * 3 |
| 192 | |
Georg Brandl | bdbdfb1 | 2011-08-08 21:45:13 +0200 | [diff] [blame] | 193 | (Yes, this is the correct code. Look closely: the ``else`` clause belongs to |
| 194 | the :keyword:`for` loop, **not** the :keyword:`if` statement.) |
| 195 | |
Nick Coghlan | a3a164a | 2012-06-07 22:41:34 +1000 | [diff] [blame] | 196 | When used with a loop, the ``else`` clause has more in common with the |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 197 | ``else`` clause of a :keyword:`try` statement than it does with that of |
| 198 | :keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs |
Nick Coghlan | a3a164a | 2012-06-07 22:41:34 +1000 | [diff] [blame] | 199 | when no exception occurs, and a loop's ``else`` clause runs when no ``break`` |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 200 | occurs. For more on the :keyword:`!try` statement and exceptions, see |
Nick Coghlan | a3a164a | 2012-06-07 22:41:34 +1000 | [diff] [blame] | 201 | :ref:`tut-handling`. |
| 202 | |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 203 | The :keyword:`continue` statement, also borrowed from C, continues with the next |
| 204 | iteration of the loop:: |
| 205 | |
| 206 | >>> for num in range(2, 10): |
Eli Bendersky | 31a1190 | 2012-08-18 09:50:09 +0300 | [diff] [blame] | 207 | ... if num % 2 == 0: |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 208 | ... print("Found an even number", num) |
| 209 | ... continue |
Neeraj Samtani | 7bcc645 | 2020-09-15 17:39:29 +0400 | [diff] [blame] | 210 | ... print("Found an odd number", num) |
Miss Islington (bot) | 48cb11b | 2021-05-12 03:25:54 -0700 | [diff] [blame] | 211 | ... |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 212 | Found an even number 2 |
Neeraj Samtani | 7bcc645 | 2020-09-15 17:39:29 +0400 | [diff] [blame] | 213 | Found an odd number 3 |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 214 | Found an even number 4 |
Neeraj Samtani | 7bcc645 | 2020-09-15 17:39:29 +0400 | [diff] [blame] | 215 | Found an odd number 5 |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 216 | Found an even number 6 |
Neeraj Samtani | 7bcc645 | 2020-09-15 17:39:29 +0400 | [diff] [blame] | 217 | Found an odd number 7 |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 218 | Found an even number 8 |
Neeraj Samtani | 7bcc645 | 2020-09-15 17:39:29 +0400 | [diff] [blame] | 219 | Found an odd number 9 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 220 | |
| 221 | .. _tut-pass: |
| 222 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 223 | :keyword:`!pass` Statements |
| 224 | =========================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 225 | |
| 226 | The :keyword:`pass` statement does nothing. It can be used when a statement is |
| 227 | required syntactically but the program requires no action. For example:: |
| 228 | |
| 229 | >>> while True: |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 230 | ... pass # Busy-wait for keyboard interrupt (Ctrl+C) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 231 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 232 | |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 233 | This is commonly used for creating minimal classes:: |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 234 | |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 235 | >>> class MyEmptyClass: |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 236 | ... pass |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 237 | ... |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 238 | |
| 239 | Another place :keyword:`pass` can be used is as a place-holder for a function or |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 240 | conditional body when you are working on new code, allowing you to keep thinking |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 241 | at a more abstract level. The :keyword:`!pass` is silently ignored:: |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 242 | |
| 243 | >>> def initlog(*args): |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 244 | ... pass # Remember to implement this! |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 245 | ... |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 246 | |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 247 | |
| 248 | .. _tut-match: |
| 249 | |
| 250 | :keyword:`!match` Statements |
| 251 | ============================ |
| 252 | |
| 253 | A match statement takes an expression and compares its value to successive |
| 254 | patterns given as one or more case blocks. This is superficially |
| 255 | similar to a switch statement in C, Java or JavaScript (and many |
| 256 | other languages), but it can also extract components (sequence elements or |
| 257 | object attributes) from the value into variables. |
| 258 | |
| 259 | The simplest form compares a subject value against one or more literals:: |
| 260 | |
| 261 | def http_error(status): |
| 262 | match status: |
| 263 | case 400: |
| 264 | return "Bad request" |
| 265 | case 404: |
| 266 | return "Not found" |
| 267 | case 418: |
| 268 | return "I'm a teapot" |
| 269 | case _: |
Miss Islington (bot) | 6fc1efa | 2021-07-26 15:34:32 -0700 | [diff] [blame] | 270 | return "Something's wrong with the internet" |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 271 | |
| 272 | Note the last block: the "variable name" ``_`` acts as a *wildcard* and |
| 273 | never fails to match. If no case matches, none of the branches is executed. |
| 274 | |
| 275 | You can combine several literals in a single pattern using ``|`` ("or"):: |
| 276 | |
| 277 | case 401 | 403 | 404: |
| 278 | return "Not allowed" |
| 279 | |
| 280 | Patterns can look like unpacking assignments, and can be used to bind |
| 281 | variables:: |
| 282 | |
| 283 | # point is an (x, y) tuple |
| 284 | match point: |
| 285 | case (0, 0): |
| 286 | print("Origin") |
| 287 | case (0, y): |
| 288 | print(f"Y={y}") |
| 289 | case (x, 0): |
| 290 | print(f"X={x}") |
| 291 | case (x, y): |
| 292 | print(f"X={x}, Y={y}") |
| 293 | case _: |
| 294 | raise ValueError("Not a point") |
| 295 | |
| 296 | Study that one carefully! The first pattern has two literals, and can |
| 297 | be thought of as an extension of the literal pattern shown above. But |
| 298 | the next two patterns combine a literal and a variable, and the |
| 299 | variable *binds* a value from the subject (``point``). The fourth |
| 300 | pattern captures two values, which makes it conceptually similar to |
| 301 | the unpacking assignment ``(x, y) = point``. |
| 302 | |
| 303 | If you are using classes to structure your data |
| 304 | you can use the class name followed by an argument list resembling a |
| 305 | constructor, but with the ability to capture attributes into variables:: |
| 306 | |
| 307 | class Point: |
| 308 | x: int |
| 309 | y: int |
| 310 | |
| 311 | def where_is(point): |
| 312 | match point: |
| 313 | case Point(x=0, y=0): |
| 314 | print("Origin") |
| 315 | case Point(x=0, y=y): |
| 316 | print(f"Y={y}") |
| 317 | case Point(x=x, y=0): |
| 318 | print(f"X={x}") |
| 319 | case Point(): |
| 320 | print("Somewhere else") |
| 321 | case _: |
| 322 | print("Not a point") |
| 323 | |
| 324 | You can use positional parameters with some builtin classes that provide an |
| 325 | ordering for their attributes (e.g. dataclasses). You can also define a specific |
| 326 | position for attributes in patterns by setting the ``__match_args__`` special |
| 327 | attribute in your classes. If it's set to ("x", "y"), the following patterns are all |
| 328 | equivalent (and all bind the ``y`` attribute to the ``var`` variable):: |
| 329 | |
| 330 | Point(1, var) |
| 331 | Point(1, y=var) |
| 332 | Point(x=1, y=var) |
| 333 | Point(y=var, x=1) |
| 334 | |
| 335 | A recommended way to read patterns is to look at them as an extended form of what you |
| 336 | would put on the left of an assignment, to understand which variables would be set to |
| 337 | what. |
| 338 | Only the standalone names (like ``var`` above) are assigned to by a match statement. |
| 339 | Dotted names (like ``foo.bar``), attribute names (the ``x=`` and ``y=`` above) or class names |
| 340 | (recognized by the "(...)" next to them like ``Point`` above) are never assigned to. |
| 341 | |
| 342 | Patterns can be arbitrarily nested. For example, if we have a short |
| 343 | list of points, we could match it like this:: |
| 344 | |
| 345 | match points: |
| 346 | case []: |
| 347 | print("No points") |
| 348 | case [Point(0, 0)]: |
| 349 | print("The origin") |
| 350 | case [Point(x, y)]: |
| 351 | print(f"Single point {x}, {y}") |
| 352 | case [Point(0, y1), Point(0, y2)]: |
| 353 | print(f"Two on the Y axis at {y1}, {y2}") |
| 354 | case _: |
| 355 | print("Something else") |
| 356 | |
| 357 | We can add an ``if`` clause to a pattern, known as a "guard". If the |
| 358 | guard is false, ``match`` goes on to try the next case block. Note |
| 359 | that value capture happens before the guard is evaluated:: |
| 360 | |
| 361 | match point: |
| 362 | case Point(x, y) if x == y: |
| 363 | print(f"Y=X at {x}") |
| 364 | case Point(x, y): |
| 365 | print(f"Not on the diagonal") |
| 366 | |
| 367 | Several other key features of this statement: |
| 368 | |
| 369 | - Like unpacking assignments, tuple and list patterns have exactly the |
| 370 | same meaning and actually match arbitrary sequences. An important |
| 371 | exception is that they don't match iterators or strings. |
| 372 | |
| 373 | - Sequence patterns support extended unpacking: ``[x, y, *rest]`` and ``(x, y, |
| 374 | *rest)`` work similar to unpacking assignments. The |
| 375 | name after ``*`` may also be ``_``, so ``(x, y, *_)`` matches a sequence |
| 376 | of at least two items without binding the remaining items. |
| 377 | |
| 378 | - Mapping patterns: ``{"bandwidth": b, "latency": l}`` captures the |
| 379 | ``"bandwidth"`` and ``"latency"`` values from a dictionary. Unlike sequence |
| 380 | patterns, extra keys are ignored. An unpacking like ``**rest`` is also |
Miss Islington (bot) | 2c47922 | 2021-11-08 09:13:02 -0800 | [diff] [blame^] | 381 | supported. (But ``**_`` would be redundant, so it is not allowed.) |
Daniel F Moisset | a22bca6 | 2021-03-01 04:08:38 +0000 | [diff] [blame] | 382 | |
| 383 | - Subpatterns may be captured using the ``as`` keyword:: |
| 384 | |
| 385 | case (Point(x1, y1), Point(x2, y2) as p2): ... |
| 386 | |
| 387 | will capture the second element of the input as ``p2`` (as long as the input is |
| 388 | a sequence of two points) |
| 389 | |
| 390 | - Most literals are compared by equality, however the singletons ``True``, |
| 391 | ``False`` and ``None`` are compared by identity. |
| 392 | |
| 393 | - Patterns may use named constants. These must be dotted names |
| 394 | to prevent them from being interpreted as capture variable:: |
| 395 | |
| 396 | from enum import Enum |
| 397 | class Color(Enum): |
| 398 | RED = 0 |
| 399 | GREEN = 1 |
| 400 | BLUE = 2 |
| 401 | |
| 402 | match color: |
| 403 | case Color.RED: |
| 404 | print("I see red!") |
| 405 | case Color.GREEN: |
| 406 | print("Grass is green") |
| 407 | case Color.BLUE: |
| 408 | print("I'm feeling the blues :(") |
| 409 | |
| 410 | For a more detailed explanation and additional examples, you can look into |
| 411 | :pep:`636` which is written in a tutorial format. |
| 412 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | .. _tut-functions: |
| 414 | |
| 415 | Defining Functions |
| 416 | ================== |
| 417 | |
| 418 | We can create a function that writes the Fibonacci series to an arbitrary |
| 419 | boundary:: |
| 420 | |
| 421 | >>> def fib(n): # write Fibonacci series up to n |
| 422 | ... """Print a Fibonacci series up to n.""" |
| 423 | ... a, b = 0, 1 |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 424 | ... while a < n: |
| 425 | ... print(a, end=' ') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 426 | ... a, b = b, a+b |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 427 | ... print() |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 428 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 429 | >>> # Now call the function we just defined: |
| 430 | ... fib(2000) |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 431 | 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | |
| 433 | .. index:: |
| 434 | single: documentation strings |
| 435 | single: docstrings |
| 436 | single: strings, documentation |
| 437 | |
| 438 | The keyword :keyword:`def` introduces a function *definition*. It must be |
| 439 | followed by the function name and the parenthesized list of formal parameters. |
| 440 | The statements that form the body of the function start at the next line, and |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 441 | must be indented. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 442 | |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 443 | The first statement of the function body can optionally be a string literal; |
| 444 | this string literal is the function's documentation string, or :dfn:`docstring`. |
| 445 | (More about docstrings can be found in the section :ref:`tut-docstrings`.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 446 | There are tools which use docstrings to automatically produce online or printed |
| 447 | documentation, or to let the user interactively browse through code; it's good |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 448 | practice to include docstrings in code that you write, so make a habit of it. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 449 | |
| 450 | The *execution* of a function introduces a new symbol table used for the local |
| 451 | variables of the function. More precisely, all variable assignments in a |
| 452 | function store the value in the local symbol table; whereas variable references |
Georg Brandl | 86def6c | 2008-01-21 20:36:10 +0000 | [diff] [blame] | 453 | first look in the local symbol table, then in the local symbol tables of |
| 454 | enclosing functions, then in the global symbol table, and finally in the table |
pbhd | e1f95e7 | 2019-05-29 05:38:03 +0200 | [diff] [blame] | 455 | of built-in names. Thus, global variables and variables of enclosing functions |
| 456 | cannot be directly assigned a value within a function (unless, for global |
| 457 | variables, named in a :keyword:`global` statement, or, for variables of enclosing |
| 458 | functions, named in a :keyword:`nonlocal` statement), although they may be |
| 459 | referenced. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 460 | |
| 461 | The actual parameters (arguments) to a function call are introduced in the local |
| 462 | symbol table of the called function when it is called; thus, arguments are |
| 463 | passed using *call by value* (where the *value* is always an object *reference*, |
Terry Jan Reedy | b30fcba | 2021-02-19 19:26:21 -0500 | [diff] [blame] | 464 | not the value of the object). [#]_ When a function calls another function, |
| 465 | or calls itself recursively, a new |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 466 | local symbol table is created for that call. |
| 467 | |
Joannah Nanjekye | d12af71 | 2020-07-05 22:47:15 -0300 | [diff] [blame] | 468 | A function definition associates the function name with the function object in |
| 469 | the current symbol table. The interpreter recognizes the object pointed to by |
| 470 | that name as a user-defined function. Other names can also point to that same |
| 471 | function object and can also be used to access the function:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 472 | |
| 473 | >>> fib |
| 474 | <function fib at 10042ed0> |
| 475 | >>> f = fib |
| 476 | >>> f(100) |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 477 | 0 1 1 2 3 5 8 13 21 34 55 89 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 478 | |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 479 | Coming from other languages, you might object that ``fib`` is not a function but |
| 480 | a procedure since it doesn't return a value. In fact, even functions without a |
| 481 | :keyword:`return` statement do return a value, albeit a rather boring one. This |
| 482 | value is called ``None`` (it's a built-in name). Writing the value ``None`` is |
| 483 | normally suppressed by the interpreter if it would be the only value written. |
| 484 | You can see it if you really want to using :func:`print`:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 485 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 486 | >>> fib(0) |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 487 | >>> print(fib(0)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 488 | None |
| 489 | |
| 490 | It is simple to write a function that returns a list of the numbers of the |
| 491 | Fibonacci series, instead of printing it:: |
| 492 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 493 | >>> def fib2(n): # return Fibonacci series up to n |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 494 | ... """Return a list containing the Fibonacci series up to n.""" |
| 495 | ... result = [] |
| 496 | ... a, b = 0, 1 |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 497 | ... while a < n: |
| 498 | ... result.append(a) # see below |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 499 | ... a, b = b, a+b |
| 500 | ... return result |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 501 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 502 | >>> f100 = fib2(100) # call it |
| 503 | >>> f100 # write the result |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 504 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 505 | |
| 506 | This example, as usual, demonstrates some new Python features: |
| 507 | |
| 508 | * The :keyword:`return` statement returns with a value from a function. |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 509 | :keyword:`!return` without an expression argument returns ``None``. Falling off |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 510 | the end of a function also returns ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 511 | |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 512 | * The statement ``result.append(a)`` calls a *method* of the list object |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 513 | ``result``. A method is a function that 'belongs' to an object and is named |
| 514 | ``obj.methodname``, where ``obj`` is some object (this may be an expression), |
| 515 | and ``methodname`` is the name of a method that is defined by the object's type. |
| 516 | Different types define different methods. Methods of different types may have |
| 517 | the same name without causing ambiguity. (It is possible to define your own |
Georg Brandl | c6c3178 | 2009-06-08 13:41:29 +0000 | [diff] [blame] | 518 | object types and methods, using *classes*, see :ref:`tut-classes`) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 519 | The method :meth:`append` shown in the example is defined for list objects; it |
| 520 | adds a new element at the end of the list. In this example it is equivalent to |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 521 | ``result = result + [a]``, but more efficient. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 522 | |
| 523 | |
| 524 | .. _tut-defining: |
| 525 | |
| 526 | More on Defining Functions |
| 527 | ========================== |
| 528 | |
| 529 | It is also possible to define functions with a variable number of arguments. |
| 530 | There are three forms, which can be combined. |
| 531 | |
| 532 | |
| 533 | .. _tut-defaultargs: |
| 534 | |
| 535 | Default Argument Values |
| 536 | ----------------------- |
| 537 | |
| 538 | The most useful form is to specify a default value for one or more arguments. |
| 539 | This creates a function that can be called with fewer arguments than it is |
| 540 | defined to allow. For example:: |
| 541 | |
Berker Peksag | 0a5120e | 2016-06-02 11:31:19 -0700 | [diff] [blame] | 542 | def ask_ok(prompt, retries=4, reminder='Please try again!'): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 543 | while True: |
Georg Brandl | e9af284 | 2007-08-17 05:54:09 +0000 | [diff] [blame] | 544 | ok = input(prompt) |
Georg Brandl | c6c3178 | 2009-06-08 13:41:29 +0000 | [diff] [blame] | 545 | if ok in ('y', 'ye', 'yes'): |
| 546 | return True |
| 547 | if ok in ('n', 'no', 'nop', 'nope'): |
| 548 | return False |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 549 | retries = retries - 1 |
Collin Winter | 58721bc | 2007-09-10 00:39:52 +0000 | [diff] [blame] | 550 | if retries < 0: |
Berker Peksag | 0a5120e | 2016-06-02 11:31:19 -0700 | [diff] [blame] | 551 | raise ValueError('invalid user response') |
| 552 | print(reminder) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 553 | |
Georg Brandl | c6c3178 | 2009-06-08 13:41:29 +0000 | [diff] [blame] | 554 | This function can be called in several ways: |
| 555 | |
| 556 | * giving only the mandatory argument: |
| 557 | ``ask_ok('Do you really want to quit?')`` |
| 558 | * giving one of the optional arguments: |
| 559 | ``ask_ok('OK to overwrite the file?', 2)`` |
| 560 | * or even giving all arguments: |
| 561 | ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 562 | |
| 563 | This example also introduces the :keyword:`in` keyword. This tests whether or |
| 564 | not a sequence contains a certain value. |
| 565 | |
| 566 | The default values are evaluated at the point of function definition in the |
| 567 | *defining* scope, so that :: |
| 568 | |
| 569 | i = 5 |
| 570 | |
| 571 | def f(arg=i): |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 572 | print(arg) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 573 | |
| 574 | i = 6 |
| 575 | f() |
| 576 | |
| 577 | will print ``5``. |
| 578 | |
| 579 | **Important warning:** The default value is evaluated only once. This makes a |
| 580 | difference when the default is a mutable object such as a list, dictionary, or |
| 581 | instances of most classes. For example, the following function accumulates the |
| 582 | arguments passed to it on subsequent calls:: |
| 583 | |
| 584 | def f(a, L=[]): |
| 585 | L.append(a) |
| 586 | return L |
| 587 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 588 | print(f(1)) |
| 589 | print(f(2)) |
| 590 | print(f(3)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 591 | |
| 592 | This will print :: |
| 593 | |
| 594 | [1] |
| 595 | [1, 2] |
| 596 | [1, 2, 3] |
| 597 | |
| 598 | If you don't want the default to be shared between subsequent calls, you can |
| 599 | write the function like this instead:: |
| 600 | |
| 601 | def f(a, L=None): |
| 602 | if L is None: |
| 603 | L = [] |
| 604 | L.append(a) |
| 605 | return L |
| 606 | |
| 607 | |
| 608 | .. _tut-keywordargs: |
| 609 | |
| 610 | Keyword Arguments |
| 611 | ----------------- |
| 612 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 613 | Functions can also be called using :term:`keyword arguments <keyword argument>` |
| 614 | of the form ``kwarg=value``. For instance, the following function:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 615 | |
| 616 | def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 617 | print("-- This parrot wouldn't", action, end=' ') |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 618 | print("if you put", voltage, "volts through it.") |
| 619 | print("-- Lovely plumage, the", type) |
| 620 | print("-- It's", state, "!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 621 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 622 | accepts one required argument (``voltage``) and three optional arguments |
| 623 | (``state``, ``action``, and ``type``). This function can be called in any |
| 624 | of the following ways:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 625 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 626 | parrot(1000) # 1 positional argument |
| 627 | parrot(voltage=1000) # 1 keyword argument |
| 628 | parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments |
| 629 | parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments |
| 630 | parrot('a million', 'bereft of life', 'jump') # 3 positional arguments |
| 631 | parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 632 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 633 | but all the following calls would be invalid:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 634 | |
| 635 | parrot() # required argument missing |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 636 | parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument |
| 637 | parrot(110, voltage=220) # duplicate value for the same argument |
| 638 | parrot(actor='John Cleese') # unknown keyword argument |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 639 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 640 | In a function call, keyword arguments must follow positional arguments. |
| 641 | All the keyword arguments passed must match one of the arguments |
| 642 | accepted by the function (e.g. ``actor`` is not a valid argument for the |
| 643 | ``parrot`` function), and their order is not important. This also includes |
| 644 | non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too). |
| 645 | No argument may receive a value more than once. |
| 646 | Here's an example that fails due to this restriction:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 647 | |
| 648 | >>> def function(a): |
| 649 | ... pass |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 650 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 651 | >>> function(0, a=0) |
| 652 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 653 | File "<stdin>", line 1, in <module> |
Miss Islington (bot) | 25122b2 | 2021-08-13 17:25:11 -0700 | [diff] [blame] | 654 | TypeError: function() got multiple values for argument 'a' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 655 | |
| 656 | When a final formal parameter of the form ``**name`` is present, it receives a |
| 657 | dictionary (see :ref:`typesmapping`) containing all keyword arguments except for |
| 658 | those corresponding to a formal parameter. This may be combined with a formal |
| 659 | parameter of the form ``*name`` (described in the next subsection) which |
Julien Palard | 51ddab8 | 2019-05-28 15:10:23 +0200 | [diff] [blame] | 660 | receives a :ref:`tuple <tut-tuples>` containing the positional |
| 661 | arguments beyond the formal parameter list. (``*name`` must occur |
| 662 | before ``**name``.) For example, if we define a function like this:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 663 | |
| 664 | def cheeseshop(kind, *arguments, **keywords): |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 665 | print("-- Do you have any", kind, "?") |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 666 | print("-- I'm sorry, we're all out of", kind) |
Georg Brandl | 70543ac | 2010-10-15 15:32:05 +0000 | [diff] [blame] | 667 | for arg in arguments: |
| 668 | print(arg) |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 669 | print("-" * 40) |
Jim Fasarakis-Hilliard | 32e8f9b | 2017-02-21 08:20:23 +0200 | [diff] [blame] | 670 | for kw in keywords: |
Georg Brandl | 70543ac | 2010-10-15 15:32:05 +0000 | [diff] [blame] | 671 | print(kw, ":", keywords[kw]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 672 | |
| 673 | It could be called like this:: |
| 674 | |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 675 | cheeseshop("Limburger", "It's very runny, sir.", |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 676 | "It's really very, VERY runny, sir.", |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 677 | shopkeeper="Michael Palin", |
| 678 | client="John Cleese", |
| 679 | sketch="Cheese Shop Sketch") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 680 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 681 | and of course it would print: |
| 682 | |
| 683 | .. code-block:: none |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 684 | |
| 685 | -- Do you have any Limburger ? |
| 686 | -- I'm sorry, we're all out of Limburger |
| 687 | It's very runny, sir. |
| 688 | It's really very, VERY runny, sir. |
| 689 | ---------------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 690 | shopkeeper : Michael Palin |
Jim Fasarakis-Hilliard | 32e8f9b | 2017-02-21 08:20:23 +0200 | [diff] [blame] | 691 | client : John Cleese |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 692 | sketch : Cheese Shop Sketch |
| 693 | |
Jim Fasarakis-Hilliard | 32e8f9b | 2017-02-21 08:20:23 +0200 | [diff] [blame] | 694 | Note that the order in which the keyword arguments are printed is guaranteed |
| 695 | to match the order in which they were provided in the function call. |
| 696 | |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 697 | Special parameters |
| 698 | ------------------ |
| 699 | |
| 700 | By default, arguments may be passed to a Python function either by position |
| 701 | or explicitly by keyword. For readability and performance, it makes sense to |
| 702 | restrict the way arguments can be passed so that a developer need only look |
| 703 | at the function definition to determine if items are passed by position, by |
| 704 | position or keyword, or by keyword. |
| 705 | |
| 706 | A function definition may look like: |
| 707 | |
| 708 | .. code-block:: none |
| 709 | |
| 710 | def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): |
| 711 | ----------- ---------- ---------- |
| 712 | | | | |
| 713 | | Positional or keyword | |
| 714 | | - Keyword only |
| 715 | -- Positional only |
| 716 | |
| 717 | where ``/`` and ``*`` are optional. If used, these symbols indicate the kind of |
| 718 | parameter by how the arguments may be passed to the function: |
| 719 | positional-only, positional-or-keyword, and keyword-only. Keyword parameters |
| 720 | are also referred to as named parameters. |
| 721 | |
| 722 | ------------------------------- |
| 723 | Positional-or-Keyword Arguments |
| 724 | ------------------------------- |
| 725 | |
| 726 | If ``/`` and ``*`` are not present in the function definition, arguments may |
| 727 | be passed to a function by position or by keyword. |
| 728 | |
| 729 | -------------------------- |
| 730 | Positional-Only Parameters |
| 731 | -------------------------- |
| 732 | |
| 733 | Looking at this in a bit more detail, it is possible to mark certain parameters |
| 734 | as *positional-only*. If *positional-only*, the parameters' order matters, and |
| 735 | the parameters cannot be passed by keyword. Positional-only parameters are |
| 736 | placed before a ``/`` (forward-slash). The ``/`` is used to logically |
| 737 | separate the positional-only parameters from the rest of the parameters. |
| 738 | If there is no ``/`` in the function definition, there are no positional-only |
| 739 | parameters. |
| 740 | |
| 741 | Parameters following the ``/`` may be *positional-or-keyword* or *keyword-only*. |
| 742 | |
| 743 | ---------------------- |
| 744 | Keyword-Only Arguments |
| 745 | ---------------------- |
| 746 | |
| 747 | To mark parameters as *keyword-only*, indicating the parameters must be passed |
| 748 | by keyword argument, place an ``*`` in the arguments list just before the first |
| 749 | *keyword-only* parameter. |
| 750 | |
| 751 | ----------------- |
| 752 | Function Examples |
| 753 | ----------------- |
| 754 | |
| 755 | Consider the following example function definitions paying close attention to the |
| 756 | markers ``/`` and ``*``:: |
| 757 | |
| 758 | >>> def standard_arg(arg): |
| 759 | ... print(arg) |
| 760 | ... |
| 761 | >>> def pos_only_arg(arg, /): |
| 762 | ... print(arg) |
| 763 | ... |
| 764 | >>> def kwd_only_arg(*, arg): |
| 765 | ... print(arg) |
| 766 | ... |
| 767 | >>> def combined_example(pos_only, /, standard, *, kwd_only): |
| 768 | ... print(pos_only, standard, kwd_only) |
| 769 | |
| 770 | |
| 771 | The first function definition, ``standard_arg``, the most familiar form, |
| 772 | places no restrictions on the calling convention and arguments may be |
| 773 | passed by position or keyword:: |
| 774 | |
| 775 | >>> standard_arg(2) |
| 776 | 2 |
| 777 | |
| 778 | >>> standard_arg(arg=2) |
| 779 | 2 |
| 780 | |
| 781 | The second function ``pos_only_arg`` is restricted to only use positional |
| 782 | parameters as there is a ``/`` in the function definition:: |
| 783 | |
| 784 | >>> pos_only_arg(1) |
| 785 | 1 |
| 786 | |
| 787 | >>> pos_only_arg(arg=1) |
| 788 | Traceback (most recent call last): |
| 789 | File "<stdin>", line 1, in <module> |
Miss Islington (bot) | 25122b2 | 2021-08-13 17:25:11 -0700 | [diff] [blame] | 790 | TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg' |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 791 | |
| 792 | The third function ``kwd_only_args`` only allows keyword arguments as indicated |
| 793 | by a ``*`` in the function definition:: |
| 794 | |
| 795 | >>> kwd_only_arg(3) |
| 796 | Traceback (most recent call last): |
| 797 | File "<stdin>", line 1, in <module> |
| 798 | TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given |
| 799 | |
| 800 | >>> kwd_only_arg(arg=3) |
| 801 | 3 |
| 802 | |
| 803 | And the last uses all three calling conventions in the same function |
| 804 | definition:: |
| 805 | |
| 806 | >>> combined_example(1, 2, 3) |
| 807 | Traceback (most recent call last): |
| 808 | File "<stdin>", line 1, in <module> |
| 809 | TypeError: combined_example() takes 2 positional arguments but 3 were given |
| 810 | |
| 811 | >>> combined_example(1, 2, kwd_only=3) |
| 812 | 1 2 3 |
| 813 | |
| 814 | >>> combined_example(1, standard=2, kwd_only=3) |
| 815 | 1 2 3 |
| 816 | |
| 817 | >>> combined_example(pos_only=1, standard=2, kwd_only=3) |
| 818 | Traceback (most recent call last): |
| 819 | File "<stdin>", line 1, in <module> |
Miss Islington (bot) | 25122b2 | 2021-08-13 17:25:11 -0700 | [diff] [blame] | 820 | TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only' |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 821 | |
| 822 | |
| 823 | Finally, consider this function definition which has a potential collision between the positional argument ``name`` and ``**kwds`` which has ``name`` as a key:: |
| 824 | |
| 825 | def foo(name, **kwds): |
| 826 | return 'name' in kwds |
| 827 | |
| 828 | There is no possible call that will make it return ``True`` as the keyword ``'name'`` |
Denis Ovsienko | 0be7c21 | 2020-08-19 12:29:47 +0100 | [diff] [blame] | 829 | will always bind to the first parameter. For example:: |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 830 | |
| 831 | >>> foo(1, **{'name': 2}) |
| 832 | Traceback (most recent call last): |
| 833 | File "<stdin>", line 1, in <module> |
| 834 | TypeError: foo() got multiple values for argument 'name' |
| 835 | >>> |
| 836 | |
| 837 | But using ``/`` (positional only arguments), it is possible since it allows ``name`` as a positional argument and ``'name'`` as a key in the keyword arguments:: |
| 838 | |
| 839 | def foo(name, /, **kwds): |
| 840 | return 'name' in kwds |
| 841 | >>> foo(1, **{'name': 2}) |
| 842 | True |
| 843 | |
| 844 | In other words, the names of positional-only parameters can be used in |
| 845 | ``**kwds`` without ambiguity. |
| 846 | |
| 847 | ----- |
| 848 | Recap |
| 849 | ----- |
| 850 | |
| 851 | The use case will determine which parameters to use in the function definition:: |
| 852 | |
| 853 | def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): |
| 854 | |
| 855 | As guidance: |
| 856 | |
| 857 | * Use positional-only if you want the name of the parameters to not be |
| 858 | available to the user. This is useful when parameter names have no real |
| 859 | meaning, if you want to enforce the order of the arguments when the function |
| 860 | is called or if you need to take some positional parameters and arbitrary |
| 861 | keywords. |
| 862 | * Use keyword-only when names have meaning and the function definition is |
| 863 | more understandable by being explicit with names or you want to prevent |
| 864 | users relying on the position of the argument being passed. |
Adorilson Bezerra | b7af4e7 | 2019-09-16 04:04:58 -0300 | [diff] [blame] | 865 | * For an API, use positional-only to prevent breaking API changes |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 866 | if the parameter's name is modified in the future. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 867 | |
| 868 | .. _tut-arbitraryargs: |
| 869 | |
| 870 | Arbitrary Argument Lists |
| 871 | ------------------------ |
| 872 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 873 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 874 | single: * (asterisk); in function calls |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 875 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 876 | Finally, the least frequently used option is to specify that a function can be |
| 877 | called with an arbitrary number of arguments. These arguments will be wrapped |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 878 | up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments, |
| 879 | zero or more normal arguments may occur. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 880 | |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 881 | def write_multiple_items(file, separator, *args): |
| 882 | file.write(separator.join(args)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 883 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 884 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 885 | Normally, these ``variadic`` arguments will be last in the list of formal |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 886 | parameters, because they scoop up all remaining input arguments that are |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 887 | passed to the function. Any formal parameters which occur after the ``*args`` |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 888 | parameter are 'keyword-only' arguments, meaning that they can only be used as |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 889 | keywords rather than positional arguments. :: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 890 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 891 | >>> def concat(*args, sep="/"): |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 892 | ... return sep.join(args) |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 893 | ... |
| 894 | >>> concat("earth", "mars", "venus") |
| 895 | 'earth/mars/venus' |
| 896 | >>> concat("earth", "mars", "venus", sep=".") |
| 897 | 'earth.mars.venus' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 898 | |
| 899 | .. _tut-unpacking-arguments: |
| 900 | |
| 901 | Unpacking Argument Lists |
| 902 | ------------------------ |
| 903 | |
| 904 | The reverse situation occurs when the arguments are already in a list or tuple |
| 905 | but need to be unpacked for a function call requiring separate positional |
| 906 | arguments. For instance, the built-in :func:`range` function expects separate |
| 907 | *start* and *stop* arguments. If they are not available separately, write the |
Raymond Hettinger | fb28fcc | 2019-03-27 21:03:02 -0700 | [diff] [blame] | 908 | function call with the ``*``\ -operator to unpack the arguments out of a list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 909 | or tuple:: |
| 910 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 911 | >>> list(range(3, 6)) # normal call with separate arguments |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 912 | [3, 4, 5] |
| 913 | >>> args = [3, 6] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 914 | >>> list(range(*args)) # call with arguments unpacked from a list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 915 | [3, 4, 5] |
| 916 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 917 | .. index:: |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 918 | single: **; in function calls |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 919 | |
Serhiy Storchaka | 3f819ca | 2018-10-31 02:26:06 +0200 | [diff] [blame] | 920 | In the same fashion, dictionaries can deliver keyword arguments with the |
Raymond Hettinger | fb28fcc | 2019-03-27 21:03:02 -0700 | [diff] [blame] | 921 | ``**``\ -operator:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 922 | |
| 923 | >>> def parrot(voltage, state='a stiff', action='voom'): |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 924 | ... print("-- This parrot wouldn't", action, end=' ') |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 925 | ... print("if you put", voltage, "volts through it.", end=' ') |
| 926 | ... print("E's", state, "!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 927 | ... |
| 928 | >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} |
| 929 | >>> parrot(**d) |
| 930 | -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised ! |
| 931 | |
| 932 | |
| 933 | .. _tut-lambda: |
| 934 | |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 935 | Lambda Expressions |
| 936 | ------------------ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 937 | |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 938 | Small anonymous functions can be created with the :keyword:`lambda` keyword. |
| 939 | This function returns the sum of its two arguments: ``lambda a, b: a+b``. |
Georg Brandl | 242e6a0 | 2013-10-06 10:28:39 +0200 | [diff] [blame] | 940 | Lambda functions can be used wherever function objects are required. They are |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 941 | syntactically restricted to a single expression. Semantically, they are just |
| 942 | syntactic sugar for a normal function definition. Like nested function |
| 943 | definitions, lambda functions can reference variables from the containing |
| 944 | scope:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 945 | |
| 946 | >>> def make_incrementor(n): |
| 947 | ... return lambda x: x + n |
| 948 | ... |
| 949 | >>> f = make_incrementor(42) |
| 950 | >>> f(0) |
| 951 | 42 |
| 952 | >>> f(1) |
| 953 | 43 |
| 954 | |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 955 | The above example uses a lambda expression to return a function. Another use |
| 956 | is to pass a small function as an argument:: |
| 957 | |
| 958 | >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] |
| 959 | >>> pairs.sort(key=lambda pair: pair[1]) |
| 960 | >>> pairs |
| 961 | [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] |
| 962 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 963 | |
| 964 | .. _tut-docstrings: |
| 965 | |
| 966 | Documentation Strings |
| 967 | --------------------- |
| 968 | |
| 969 | .. index:: |
| 970 | single: docstrings |
| 971 | single: documentation strings |
| 972 | single: strings, documentation |
| 973 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 974 | Here are some conventions about the content and formatting of documentation |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 975 | strings. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 976 | |
| 977 | The first line should always be a short, concise summary of the object's |
| 978 | purpose. For brevity, it should not explicitly state the object's name or type, |
| 979 | since these are available by other means (except if the name happens to be a |
| 980 | verb describing a function's operation). This line should begin with a capital |
| 981 | letter and end with a period. |
| 982 | |
| 983 | If there are more lines in the documentation string, the second line should be |
| 984 | blank, visually separating the summary from the rest of the description. The |
| 985 | following lines should be one or more paragraphs describing the object's calling |
| 986 | conventions, its side effects, etc. |
| 987 | |
| 988 | The Python parser does not strip indentation from multi-line string literals in |
| 989 | Python, so tools that process documentation have to strip indentation if |
| 990 | desired. This is done using the following convention. The first non-blank line |
| 991 | *after* the first line of the string determines the amount of indentation for |
| 992 | the entire documentation string. (We can't use the first line since it is |
| 993 | generally adjacent to the string's opening quotes so its indentation is not |
| 994 | apparent in the string literal.) Whitespace "equivalent" to this indentation is |
| 995 | then stripped from the start of all lines of the string. Lines that are |
| 996 | indented less should not occur, but if they occur all their leading whitespace |
| 997 | should be stripped. Equivalence of whitespace should be tested after expansion |
| 998 | of tabs (to 8 spaces, normally). |
| 999 | |
| 1000 | Here is an example of a multi-line docstring:: |
| 1001 | |
| 1002 | >>> def my_function(): |
| 1003 | ... """Do nothing, but document it. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1004 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1005 | ... No, really, it doesn't do anything. |
| 1006 | ... """ |
| 1007 | ... pass |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1008 | ... |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 1009 | >>> print(my_function.__doc__) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1010 | Do nothing, but document it. |
| 1011 | |
| 1012 | No, really, it doesn't do anything. |
| 1013 | |
| 1014 | |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1015 | .. _tut-annotations: |
| 1016 | |
| 1017 | Function Annotations |
| 1018 | -------------------- |
| 1019 | |
| 1020 | .. sectionauthor:: Zachary Ware <zachary.ware@gmail.com> |
| 1021 | .. index:: |
| 1022 | pair: function; annotations |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 1023 | single: ->; function annotations |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 1024 | single: : (colon); function annotations |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1025 | |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 1026 | :ref:`Function annotations <function>` are completely optional metadata |
Neeraj Badlani | 643ff71 | 2018-04-25 10:52:13 -0700 | [diff] [blame] | 1027 | information about the types used by user-defined functions (see :pep:`3107` and |
| 1028 | :pep:`484` for more information). |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1029 | |
Cheryl Sabella | b7105c9 | 2018-12-24 00:09:09 -0500 | [diff] [blame] | 1030 | :term:`Annotations <function annotation>` are stored in the :attr:`__annotations__` |
| 1031 | attribute of the function as a dictionary and have no effect on any other part of the |
| 1032 | function. Parameter annotations are defined by a colon after the parameter name, followed |
| 1033 | by an expression evaluating to the value of the annotation. Return annotations are |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1034 | defined by a literal ``->``, followed by an expression, between the parameter |
| 1035 | list and the colon denoting the end of the :keyword:`def` statement. The |
Irit Katriel | a53e9a7 | 2021-03-27 17:20:58 +0000 | [diff] [blame] | 1036 | following example has a required argument, an optional argument, and the return |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 1037 | value annotated:: |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1038 | |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 1039 | >>> def f(ham: str, eggs: str = 'eggs') -> str: |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1040 | ... print("Annotations:", f.__annotations__) |
| 1041 | ... print("Arguments:", ham, eggs) |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 1042 | ... return ham + ' and ' + eggs |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1043 | ... |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 1044 | >>> f('spam') |
| 1045 | Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>} |
| 1046 | Arguments: spam eggs |
| 1047 | 'spam and eggs' |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 1048 | |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 1049 | .. _tut-codingstyle: |
| 1050 | |
| 1051 | Intermezzo: Coding Style |
| 1052 | ======================== |
| 1053 | |
| 1054 | .. sectionauthor:: Georg Brandl <georg@python.org> |
| 1055 | .. index:: pair: coding; style |
| 1056 | |
| 1057 | Now that you are about to write longer, more complex pieces of Python, it is a |
| 1058 | good time to talk about *coding style*. Most languages can be written (or more |
| 1059 | concise, *formatted*) in different styles; some are more readable than others. |
| 1060 | Making it easy for others to read your code is always a good idea, and adopting |
| 1061 | a nice coding style helps tremendously for that. |
| 1062 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 1063 | For Python, :pep:`8` has emerged as the style guide that most projects adhere to; |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 1064 | it promotes a very readable and eye-pleasing coding style. Every Python |
| 1065 | developer should read it at some point; here are the most important points |
| 1066 | extracted for you: |
| 1067 | |
| 1068 | * Use 4-space indentation, and no tabs. |
| 1069 | |
| 1070 | 4 spaces are a good compromise between small indentation (allows greater |
| 1071 | nesting depth) and large indentation (easier to read). Tabs introduce |
| 1072 | confusion, and are best left out. |
| 1073 | |
| 1074 | * Wrap lines so that they don't exceed 79 characters. |
| 1075 | |
| 1076 | This helps users with small displays and makes it possible to have several |
| 1077 | code files side-by-side on larger displays. |
| 1078 | |
| 1079 | * Use blank lines to separate functions and classes, and larger blocks of |
| 1080 | code inside functions. |
| 1081 | |
| 1082 | * When possible, put comments on a line of their own. |
| 1083 | |
| 1084 | * Use docstrings. |
| 1085 | |
| 1086 | * Use spaces around operators and after commas, but not directly inside |
| 1087 | bracketing constructs: ``a = f(1, 2) + g(3, 4)``. |
| 1088 | |
| 1089 | * Name your classes and functions consistently; the convention is to use |
Julien Palard | 2da622f | 2019-07-08 23:06:32 +0200 | [diff] [blame] | 1090 | ``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for functions |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 1091 | and methods. Always use ``self`` as the name for the first method argument |
| 1092 | (see :ref:`tut-firstclasses` for more on classes and methods). |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 1093 | |
| 1094 | * Don't use fancy encodings if your code is meant to be used in international |
Georg Brandl | 7ae90dd | 2009-06-08 18:59:09 +0000 | [diff] [blame] | 1095 | environments. Python's default, UTF-8, or even plain ASCII work best in any |
| 1096 | case. |
| 1097 | |
| 1098 | * Likewise, don't use non-ASCII characters in identifiers if there is only the |
| 1099 | slightest chance people speaking a different language will read or maintain |
| 1100 | the code. |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 1101 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1102 | |
| 1103 | .. rubric:: Footnotes |
| 1104 | |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 1105 | .. [#] Actually, *call by object reference* would be a better description, |
| 1106 | since if a mutable object is passed, the caller will see any changes the |
| 1107 | callee makes to it (items inserted into a list). |