blob: ee2c3e5b5853c7b4fc806ea6f3fa6491ac5c7b58 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-morecontrol:
2
3***********************
4More Control Flow Tools
5***********************
6
Diego Alberto Barriga Martínezb5748132019-09-17 11:57:55 -05007Besides the :keyword:`while` statement just introduced, Python uses the usual
8flow control statements known from other languages, with some twists.
Georg Brandl116aa622007-08-15 14:28:22 +00009
10
11.. _tut-if:
12
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020013:keyword:`!if` Statements
14=========================
Georg Brandl116aa622007-08-15 14:28:22 +000015
16Perhaps the most well-known statement type is the :keyword:`if` statement. For
17example::
18
Georg Brandle9af2842007-08-17 05:54:09 +000019 >>> x = int(input("Please enter an integer: "))
Georg Brandl5d955ed2008-09-13 17:18:21 +000020 Please enter an integer: 42
Georg Brandl116aa622007-08-15 14:28:22 +000021 >>> if x < 0:
Ezio Melottie65cb192013-11-17 22:07:48 +020022 ... x = 0
23 ... print('Negative changed to zero')
Georg Brandl116aa622007-08-15 14:28:22 +000024 ... elif x == 0:
Ezio Melottie65cb192013-11-17 22:07:48 +020025 ... print('Zero')
Georg Brandl116aa622007-08-15 14:28:22 +000026 ... elif x == 1:
Ezio Melottie65cb192013-11-17 22:07:48 +020027 ... print('Single')
Georg Brandl116aa622007-08-15 14:28:22 +000028 ... else:
Ezio Melottie65cb192013-11-17 22:07:48 +020029 ... print('More')
Georg Brandl5d955ed2008-09-13 17:18:21 +000030 ...
31 More
Georg Brandl116aa622007-08-15 14:28:22 +000032
33There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020034optional. The keyword ':keyword:`!elif`' is short for 'else if', and is useful
35to avoid excessive indentation. An :keyword:`!if` ... :keyword:`!elif` ...
36:keyword:`!elif` ... sequence is a substitute for the ``switch`` or
Christian Heimes5b5e81c2007-12-31 16:14:33 +000037``case`` statements found in other languages.
Georg Brandl116aa622007-08-15 14:28:22 +000038
Daniel F Moisseta22bca62021-03-01 04:08:38 +000039If you're comparing the same value to several constants, or checking for specific types or
40attributes, you may also find the :keyword:`!match` statement useful. For more
41details see :ref:`tut-match`.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43.. _tut-for:
44
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020045:keyword:`!for` Statements
46==========================
Georg Brandl116aa622007-08-15 14:28:22 +000047
48.. index::
49 statement: for
Georg Brandl116aa622007-08-15 14:28:22 +000050
51The :keyword:`for` statement in Python differs a bit from what you may be used
52to in C or Pascal. Rather than always iterating over an arithmetic progression
53of numbers (like in Pascal), or giving the user the ability to define both the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020054iteration step and halting condition (as C), Python's :keyword:`!for` statement
Georg Brandl116aa622007-08-15 14:28:22 +000055iterates over the items of any sequence (a list or a string), in the order that
56they appear in the sequence. For example (no pun intended):
57
Christian Heimes5b5e81c2007-12-31 16:14:33 +000058.. One suggestion was to give a real C example here, but that may only serve to
59 confuse non-C programmers.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61::
62
63 >>> # Measure some strings:
Chris Jerdonek4fab8f02012-10-15 19:44:47 -070064 ... words = ['cat', 'window', 'defenestrate']
65 >>> for w in words:
66 ... print(w, len(w))
Georg Brandl48310cd2009-01-03 21:18:54 +000067 ...
Georg Brandl116aa622007-08-15 14:28:22 +000068 cat 3
69 window 6
70 defenestrate 12
71
Raymond Hettinger6fcb6cf2019-08-22 23:44:19 -070072Code that modifies a collection while iterating over that same collection can
73be tricky to get right. Instead, it is usually more straight-forward to loop
74over a copy of the collection or to create a new collection::
Georg Brandl116aa622007-08-15 14:28:22 +000075
Antoine6fad3e62020-05-23 02:29:34 +020076 # Create a sample collection
77 users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
78
Raymond Hettinger6fcb6cf2019-08-22 23:44:19 -070079 # Strategy: Iterate over a copy
80 for user, status in users.copy().items():
81 if status == 'inactive':
82 del users[user]
Georg Brandl116aa622007-08-15 14:28:22 +000083
Raymond Hettinger6fcb6cf2019-08-22 23:44:19 -070084 # 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 Brandl40383c82016-02-15 17:50:33 +010089
Georg Brandl116aa622007-08-15 14:28:22 +000090
91.. _tut-range:
92
93The :func:`range` Function
94==========================
95
96If you do need to iterate over a sequence of numbers, the built-in function
Guido van Rossum0616b792007-08-31 03:25:11 +000097:func:`range` comes in handy. It generates arithmetic progressions::
Georg Brandl116aa622007-08-15 14:28:22 +000098
Guido van Rossum0616b792007-08-31 03:25:11 +000099 >>> for i in range(5):
100 ... print(i)
101 ...
102 0
103 1
104 2
105 3
106 4
Georg Brandl48310cd2009-01-03 21:18:54 +0000107
Georg Brandl7d821062010-06-27 10:59:19 +0000108The given end point is never part of the generated sequence; ``range(10)`` generates
Guido van Rossum0616b792007-08-31 03:25:11 +000010910 values, the legal indices for items of a sequence of length 10. It
Georg Brandl116aa622007-08-15 14:28:22 +0000110is possible to let the range start at another number, or to specify a different
111increment (even negative; sometimes this is called the 'step')::
112
Georg Brandl48310cd2009-01-03 21:18:54 +0000113 range(5, 10)
Steven M. Vascellaro83d70622018-03-09 14:57:21 -0500114 5, 6, 7, 8, 9
Guido van Rossum0616b792007-08-31 03:25:11 +0000115
Georg Brandl48310cd2009-01-03 21:18:54 +0000116 range(0, 10, 3)
Guido van Rossum0616b792007-08-31 03:25:11 +0000117 0, 3, 6, 9
118
Georg Brandl48310cd2009-01-03 21:18:54 +0000119 range(-10, -100, -30)
Guido van Rossum0616b792007-08-31 03:25:11 +0000120 -10, -40, -70
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Georg Brandlaf265f42008-12-07 15:06:20 +0000122To iterate over the indices of a sequence, you can combine :func:`range` and
123:func:`len` as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
126 >>> for i in range(len(a)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000127 ... print(i, a[i])
Georg Brandl48310cd2009-01-03 21:18:54 +0000128 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000129 0 Mary
130 1 had
131 2 a
132 3 little
133 4 lamb
134
Georg Brandlaf265f42008-12-07 15:06:20 +0000135In most such cases, however, it is convenient to use the :func:`enumerate`
136function, see :ref:`tut-loopidioms`.
137
Guido van Rossum0616b792007-08-31 03:25:11 +0000138A strange thing happens if you just print a range::
139
140 >>> print(range(10))
141 range(0, 10)
142
143In many ways the object returned by :func:`range` behaves as if it is a list,
Georg Brandl48310cd2009-01-03 21:18:54 +0000144but in fact it isn't. It is an object which returns the successive items of
145the desired sequence when you iterate over it, but it doesn't really make
146the list, thus saving space.
Guido van Rossum0616b792007-08-31 03:25:11 +0000147
Marco Buttu218e47b2019-06-01 23:11:48 +0200148We say such an object is :term:`iterable`, that is, suitable as a target for
Georg Brandl48310cd2009-01-03 21:18:54 +0000149functions and constructs that expect something from which they can
Marco Buttu218e47b2019-06-01 23:11:48 +0200150obtain successive items until the supply is exhausted. We have seen that
Don Kirkby3ed4d252020-02-09 16:57:46 -0800151the :keyword:`for` statement is such a construct, while an example of a function
Marco Buttu218e47b2019-06-01 23:11:48 +0200152that takes an iterable is :func:`sum`::
Guido van Rossum0616b792007-08-31 03:25:11 +0000153
Marco Buttu218e47b2019-06-01 23:11:48 +0200154 >>> sum(range(4)) # 0 + 1 + 2 + 3
155 6
Guido van Rossum0616b792007-08-31 03:25:11 +0000156
Marco Buttu218e47b2019-06-01 23:11:48 +0200157Later we will see more functions that return iterables and take iterables as
158arguments. Lastly, maybe you are curious about how to get a list from a range.
159Here is the solution::
Guido van Rossum0616b792007-08-31 03:25:11 +0000160
Marco Buttu218e47b2019-06-01 23:11:48 +0200161 >>> list(range(4))
162 [0, 1, 2, 3]
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Marco Buttu218e47b2019-06-01 23:11:48 +0200164In chapter :ref:`tut-structures`, we will discuss in more detail about
165:func:`list`.
Georg Brandlaf265f42008-12-07 15:06:20 +0000166
Georg Brandl116aa622007-08-15 14:28:22 +0000167.. _tut-break:
168
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200169:keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` Clauses on Loops
170============================================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000171
regexaurus36fc8962017-06-27 18:40:41 -0400172The :keyword:`break` statement, like in C, breaks out of the innermost enclosing
Georg Brandl116aa622007-08-15 14:28:22 +0000173:keyword:`for` or :keyword:`while` loop.
174
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200175Loop statements may have an :keyword:`!else` clause; it is executed when the loop
Marco Buttu218e47b2019-06-01 23:11:48 +0200176terminates through exhaustion of the iterable (with :keyword:`for`) or when the
Georg Brandl116aa622007-08-15 14:28:22 +0000177condition becomes false (with :keyword:`while`), but not when the loop is
178terminated by a :keyword:`break` statement. This is exemplified by the
179following loop, which searches for prime numbers::
180
181 >>> for n in range(2, 10):
182 ... for x in range(2, n):
183 ... if n % x == 0:
Georg Brandlb03c1d92008-05-01 18:06:50 +0000184 ... print(n, 'equals', x, '*', n//x)
Georg Brandl116aa622007-08-15 14:28:22 +0000185 ... break
186 ... else:
187 ... # loop fell through without finding a factor
Guido van Rossum0616b792007-08-31 03:25:11 +0000188 ... print(n, 'is a prime number')
Georg Brandl48310cd2009-01-03 21:18:54 +0000189 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000190 2 is a prime number
191 3 is a prime number
192 4 equals 2 * 2
193 5 is a prime number
194 6 equals 2 * 3
195 7 is a prime number
196 8 equals 2 * 4
197 9 equals 3 * 3
198
Georg Brandlbdbdfb12011-08-08 21:45:13 +0200199(Yes, this is the correct code. Look closely: the ``else`` clause belongs to
200the :keyword:`for` loop, **not** the :keyword:`if` statement.)
201
Nick Coghlana3a164a2012-06-07 22:41:34 +1000202When used with a loop, the ``else`` clause has more in common with the
Marco Buttu218e47b2019-06-01 23:11:48 +0200203``else`` clause of a :keyword:`try` statement than it does with that of
204:keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs
Nick Coghlana3a164a2012-06-07 22:41:34 +1000205when no exception occurs, and a loop's ``else`` clause runs when no ``break``
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200206occurs. For more on the :keyword:`!try` statement and exceptions, see
Nick Coghlana3a164a2012-06-07 22:41:34 +1000207:ref:`tut-handling`.
208
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700209The :keyword:`continue` statement, also borrowed from C, continues with the next
210iteration of the loop::
211
212 >>> for num in range(2, 10):
Eli Bendersky31a11902012-08-18 09:50:09 +0300213 ... if num % 2 == 0:
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700214 ... print("Found an even number", num)
215 ... continue
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400216 ... print("Found an odd number", num)
Miss Islington (bot)48cb11b2021-05-12 03:25:54 -0700217 ...
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700218 Found an even number 2
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400219 Found an odd number 3
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700220 Found an even number 4
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400221 Found an odd number 5
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700222 Found an even number 6
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400223 Found an odd number 7
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700224 Found an even number 8
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400225 Found an odd number 9
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227.. _tut-pass:
228
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200229:keyword:`!pass` Statements
230===========================
Georg Brandl116aa622007-08-15 14:28:22 +0000231
232The :keyword:`pass` statement does nothing. It can be used when a statement is
233required syntactically but the program requires no action. For example::
234
235 >>> while True:
Georg Brandl5d955ed2008-09-13 17:18:21 +0000236 ... pass # Busy-wait for keyboard interrupt (Ctrl+C)
Georg Brandl48310cd2009-01-03 21:18:54 +0000237 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000238
Benjamin Peterson92035012008-12-27 16:00:54 +0000239This is commonly used for creating minimal classes::
Georg Brandla971c652008-11-07 09:39:56 +0000240
Benjamin Peterson92035012008-12-27 16:00:54 +0000241 >>> class MyEmptyClass:
Georg Brandla971c652008-11-07 09:39:56 +0000242 ... pass
Benjamin Peterson92035012008-12-27 16:00:54 +0000243 ...
Georg Brandla971c652008-11-07 09:39:56 +0000244
245Another place :keyword:`pass` can be used is as a place-holder for a function or
Benjamin Peterson92035012008-12-27 16:00:54 +0000246conditional body when you are working on new code, allowing you to keep thinking
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200247at a more abstract level. The :keyword:`!pass` is silently ignored::
Georg Brandla971c652008-11-07 09:39:56 +0000248
249 >>> def initlog(*args):
Benjamin Peterson92035012008-12-27 16:00:54 +0000250 ... pass # Remember to implement this!
Georg Brandl48310cd2009-01-03 21:18:54 +0000251 ...
Georg Brandla971c652008-11-07 09:39:56 +0000252
Daniel F Moisseta22bca62021-03-01 04:08:38 +0000253
254.. _tut-match:
255
256:keyword:`!match` Statements
257============================
258
259A match statement takes an expression and compares its value to successive
260patterns given as one or more case blocks. This is superficially
261similar to a switch statement in C, Java or JavaScript (and many
262other languages), but it can also extract components (sequence elements or
263object attributes) from the value into variables.
264
265The simplest form compares a subject value against one or more literals::
266
267 def http_error(status):
268 match status:
269 case 400:
270 return "Bad request"
271 case 404:
272 return "Not found"
273 case 418:
274 return "I'm a teapot"
275 case _:
276 return "Something's wrong with the Internet"
277
278Note the last block: the "variable name" ``_`` acts as a *wildcard* and
279never fails to match. If no case matches, none of the branches is executed.
280
281You can combine several literals in a single pattern using ``|`` ("or")::
282
283 case 401 | 403 | 404:
284 return "Not allowed"
285
286Patterns can look like unpacking assignments, and can be used to bind
287variables::
288
289 # point is an (x, y) tuple
290 match point:
291 case (0, 0):
292 print("Origin")
293 case (0, y):
294 print(f"Y={y}")
295 case (x, 0):
296 print(f"X={x}")
297 case (x, y):
298 print(f"X={x}, Y={y}")
299 case _:
300 raise ValueError("Not a point")
301
302Study that one carefully! The first pattern has two literals, and can
303be thought of as an extension of the literal pattern shown above. But
304the next two patterns combine a literal and a variable, and the
305variable *binds* a value from the subject (``point``). The fourth
306pattern captures two values, which makes it conceptually similar to
307the unpacking assignment ``(x, y) = point``.
308
309If you are using classes to structure your data
310you can use the class name followed by an argument list resembling a
311constructor, but with the ability to capture attributes into variables::
312
313 class Point:
314 x: int
315 y: int
316
317 def where_is(point):
318 match point:
319 case Point(x=0, y=0):
320 print("Origin")
321 case Point(x=0, y=y):
322 print(f"Y={y}")
323 case Point(x=x, y=0):
324 print(f"X={x}")
325 case Point():
326 print("Somewhere else")
327 case _:
328 print("Not a point")
329
330You can use positional parameters with some builtin classes that provide an
331ordering for their attributes (e.g. dataclasses). You can also define a specific
332position for attributes in patterns by setting the ``__match_args__`` special
333attribute in your classes. If it's set to ("x", "y"), the following patterns are all
334equivalent (and all bind the ``y`` attribute to the ``var`` variable)::
335
336 Point(1, var)
337 Point(1, y=var)
338 Point(x=1, y=var)
339 Point(y=var, x=1)
340
341A recommended way to read patterns is to look at them as an extended form of what you
342would put on the left of an assignment, to understand which variables would be set to
343what.
344Only the standalone names (like ``var`` above) are assigned to by a match statement.
345Dotted names (like ``foo.bar``), attribute names (the ``x=`` and ``y=`` above) or class names
346(recognized by the "(...)" next to them like ``Point`` above) are never assigned to.
347
348Patterns can be arbitrarily nested. For example, if we have a short
349list of points, we could match it like this::
350
351 match points:
352 case []:
353 print("No points")
354 case [Point(0, 0)]:
355 print("The origin")
356 case [Point(x, y)]:
357 print(f"Single point {x}, {y}")
358 case [Point(0, y1), Point(0, y2)]:
359 print(f"Two on the Y axis at {y1}, {y2}")
360 case _:
361 print("Something else")
362
363We can add an ``if`` clause to a pattern, known as a "guard". If the
364guard is false, ``match`` goes on to try the next case block. Note
365that value capture happens before the guard is evaluated::
366
367 match point:
368 case Point(x, y) if x == y:
369 print(f"Y=X at {x}")
370 case Point(x, y):
371 print(f"Not on the diagonal")
372
373Several other key features of this statement:
374
375- Like unpacking assignments, tuple and list patterns have exactly the
376 same meaning and actually match arbitrary sequences. An important
377 exception is that they don't match iterators or strings.
378
379- Sequence patterns support extended unpacking: ``[x, y, *rest]`` and ``(x, y,
380 *rest)`` work similar to unpacking assignments. The
381 name after ``*`` may also be ``_``, so ``(x, y, *_)`` matches a sequence
382 of at least two items without binding the remaining items.
383
384- Mapping patterns: ``{"bandwidth": b, "latency": l}`` captures the
385 ``"bandwidth"`` and ``"latency"`` values from a dictionary. Unlike sequence
386 patterns, extra keys are ignored. An unpacking like ``**rest`` is also
387 supported. (But ``**_`` would be redundant, so it not allowed.)
388
389- Subpatterns may be captured using the ``as`` keyword::
390
391 case (Point(x1, y1), Point(x2, y2) as p2): ...
392
393 will capture the second element of the input as ``p2`` (as long as the input is
394 a sequence of two points)
395
396- Most literals are compared by equality, however the singletons ``True``,
397 ``False`` and ``None`` are compared by identity.
398
399- Patterns may use named constants. These must be dotted names
400 to prevent them from being interpreted as capture variable::
401
402 from enum import Enum
403 class Color(Enum):
404 RED = 0
405 GREEN = 1
406 BLUE = 2
407
408 match color:
409 case Color.RED:
410 print("I see red!")
411 case Color.GREEN:
412 print("Grass is green")
413 case Color.BLUE:
414 print("I'm feeling the blues :(")
415
416For a more detailed explanation and additional examples, you can look into
417:pep:`636` which is written in a tutorial format.
418
Georg Brandl116aa622007-08-15 14:28:22 +0000419.. _tut-functions:
420
421Defining Functions
422==================
423
424We can create a function that writes the Fibonacci series to an arbitrary
425boundary::
426
427 >>> def fib(n): # write Fibonacci series up to n
428 ... """Print a Fibonacci series up to n."""
429 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000430 ... while a < n:
431 ... print(a, end=' ')
Georg Brandl116aa622007-08-15 14:28:22 +0000432 ... a, b = b, a+b
Guido van Rossum0616b792007-08-31 03:25:11 +0000433 ... print()
Georg Brandl48310cd2009-01-03 21:18:54 +0000434 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000435 >>> # Now call the function we just defined:
436 ... fib(2000)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000437 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439.. index::
440 single: documentation strings
441 single: docstrings
442 single: strings, documentation
443
444The keyword :keyword:`def` introduces a function *definition*. It must be
445followed by the function name and the parenthesized list of formal parameters.
446The statements that form the body of the function start at the next line, and
Georg Brandl5d955ed2008-09-13 17:18:21 +0000447must be indented.
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Georg Brandl5d955ed2008-09-13 17:18:21 +0000449The first statement of the function body can optionally be a string literal;
450this string literal is the function's documentation string, or :dfn:`docstring`.
451(More about docstrings can be found in the section :ref:`tut-docstrings`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000452There are tools which use docstrings to automatically produce online or printed
453documentation, or to let the user interactively browse through code; it's good
Georg Brandl5d955ed2008-09-13 17:18:21 +0000454practice to include docstrings in code that you write, so make a habit of it.
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456The *execution* of a function introduces a new symbol table used for the local
457variables of the function. More precisely, all variable assignments in a
458function store the value in the local symbol table; whereas variable references
Georg Brandl86def6c2008-01-21 20:36:10 +0000459first look in the local symbol table, then in the local symbol tables of
460enclosing functions, then in the global symbol table, and finally in the table
pbhde1f95e72019-05-29 05:38:03 +0200461of built-in names. Thus, global variables and variables of enclosing functions
462cannot be directly assigned a value within a function (unless, for global
463variables, named in a :keyword:`global` statement, or, for variables of enclosing
464functions, named in a :keyword:`nonlocal` statement), although they may be
465referenced.
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467The actual parameters (arguments) to a function call are introduced in the local
468symbol table of the called function when it is called; thus, arguments are
469passed using *call by value* (where the *value* is always an object *reference*,
Terry Jan Reedyb30fcba2021-02-19 19:26:21 -0500470not the value of the object). [#]_ When a function calls another function,
471or calls itself recursively, a new
Georg Brandl116aa622007-08-15 14:28:22 +0000472local symbol table is created for that call.
473
Joannah Nanjekyed12af712020-07-05 22:47:15 -0300474A function definition associates the function name with the function object in
475the current symbol table. The interpreter recognizes the object pointed to by
476that name as a user-defined function. Other names can also point to that same
477function object and can also be used to access the function::
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479 >>> fib
480 <function fib at 10042ed0>
481 >>> f = fib
482 >>> f(100)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000483 0 1 1 2 3 5 8 13 21 34 55 89
Georg Brandl116aa622007-08-15 14:28:22 +0000484
Georg Brandl5d955ed2008-09-13 17:18:21 +0000485Coming from other languages, you might object that ``fib`` is not a function but
486a procedure since it doesn't return a value. In fact, even functions without a
487:keyword:`return` statement do return a value, albeit a rather boring one. This
488value is called ``None`` (it's a built-in name). Writing the value ``None`` is
489normally suppressed by the interpreter if it would be the only value written.
490You can see it if you really want to using :func:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000491
Georg Brandl9afde1c2007-11-01 20:32:30 +0000492 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000493 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000494 None
495
496It is simple to write a function that returns a list of the numbers of the
497Fibonacci series, instead of printing it::
498
Serhiy Storchakadba90392016-05-10 12:01:23 +0300499 >>> def fib2(n): # return Fibonacci series up to n
Georg Brandl116aa622007-08-15 14:28:22 +0000500 ... """Return a list containing the Fibonacci series up to n."""
501 ... result = []
502 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000503 ... while a < n:
504 ... result.append(a) # see below
Georg Brandl116aa622007-08-15 14:28:22 +0000505 ... a, b = b, a+b
506 ... return result
Georg Brandl48310cd2009-01-03 21:18:54 +0000507 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000508 >>> f100 = fib2(100) # call it
509 >>> f100 # write the result
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000510 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512This example, as usual, demonstrates some new Python features:
513
514* The :keyword:`return` statement returns with a value from a function.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200515 :keyword:`!return` without an expression argument returns ``None``. Falling off
Georg Brandl5d955ed2008-09-13 17:18:21 +0000516 the end of a function also returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000518* The statement ``result.append(a)`` calls a *method* of the list object
Georg Brandl116aa622007-08-15 14:28:22 +0000519 ``result``. A method is a function that 'belongs' to an object and is named
520 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
521 and ``methodname`` is the name of a method that is defined by the object's type.
522 Different types define different methods. Methods of different types may have
523 the same name without causing ambiguity. (It is possible to define your own
Georg Brandlc6c31782009-06-08 13:41:29 +0000524 object types and methods, using *classes*, see :ref:`tut-classes`)
Georg Brandl116aa622007-08-15 14:28:22 +0000525 The method :meth:`append` shown in the example is defined for list objects; it
526 adds a new element at the end of the list. In this example it is equivalent to
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000527 ``result = result + [a]``, but more efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529
530.. _tut-defining:
531
532More on Defining Functions
533==========================
534
535It is also possible to define functions with a variable number of arguments.
536There are three forms, which can be combined.
537
538
539.. _tut-defaultargs:
540
541Default Argument Values
542-----------------------
543
544The most useful form is to specify a default value for one or more arguments.
545This creates a function that can be called with fewer arguments than it is
546defined to allow. For example::
547
Berker Peksag0a5120e2016-06-02 11:31:19 -0700548 def ask_ok(prompt, retries=4, reminder='Please try again!'):
Georg Brandl116aa622007-08-15 14:28:22 +0000549 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000550 ok = input(prompt)
Georg Brandlc6c31782009-06-08 13:41:29 +0000551 if ok in ('y', 'ye', 'yes'):
552 return True
553 if ok in ('n', 'no', 'nop', 'nope'):
554 return False
Georg Brandl116aa622007-08-15 14:28:22 +0000555 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000556 if retries < 0:
Berker Peksag0a5120e2016-06-02 11:31:19 -0700557 raise ValueError('invalid user response')
558 print(reminder)
Georg Brandl116aa622007-08-15 14:28:22 +0000559
Georg Brandlc6c31782009-06-08 13:41:29 +0000560This function can be called in several ways:
561
562* giving only the mandatory argument:
563 ``ask_ok('Do you really want to quit?')``
564* giving one of the optional arguments:
565 ``ask_ok('OK to overwrite the file?', 2)``
566* or even giving all arguments:
567 ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569This example also introduces the :keyword:`in` keyword. This tests whether or
570not a sequence contains a certain value.
571
572The default values are evaluated at the point of function definition in the
573*defining* scope, so that ::
574
575 i = 5
576
577 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000578 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580 i = 6
581 f()
582
583will print ``5``.
584
585**Important warning:** The default value is evaluated only once. This makes a
586difference when the default is a mutable object such as a list, dictionary, or
587instances of most classes. For example, the following function accumulates the
588arguments passed to it on subsequent calls::
589
590 def f(a, L=[]):
591 L.append(a)
592 return L
593
Guido van Rossum0616b792007-08-31 03:25:11 +0000594 print(f(1))
595 print(f(2))
596 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000597
598This will print ::
599
600 [1]
601 [1, 2]
602 [1, 2, 3]
603
604If you don't want the default to be shared between subsequent calls, you can
605write the function like this instead::
606
607 def f(a, L=None):
608 if L is None:
609 L = []
610 L.append(a)
611 return L
612
613
614.. _tut-keywordargs:
615
616Keyword Arguments
617-----------------
618
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200619Functions can also be called using :term:`keyword arguments <keyword argument>`
620of the form ``kwarg=value``. For instance, the following function::
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000623 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000624 print("if you put", voltage, "volts through it.")
625 print("-- Lovely plumage, the", type)
626 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200628accepts one required argument (``voltage``) and three optional arguments
629(``state``, ``action``, and ``type``). This function can be called in any
630of the following ways::
Georg Brandl116aa622007-08-15 14:28:22 +0000631
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200632 parrot(1000) # 1 positional argument
633 parrot(voltage=1000) # 1 keyword argument
634 parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
635 parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
636 parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
637 parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
Georg Brandl116aa622007-08-15 14:28:22 +0000638
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200639but all the following calls would be invalid::
Georg Brandl116aa622007-08-15 14:28:22 +0000640
641 parrot() # required argument missing
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200642 parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
643 parrot(110, voltage=220) # duplicate value for the same argument
644 parrot(actor='John Cleese') # unknown keyword argument
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200646In a function call, keyword arguments must follow positional arguments.
647All the keyword arguments passed must match one of the arguments
648accepted by the function (e.g. ``actor`` is not a valid argument for the
649``parrot`` function), and their order is not important. This also includes
650non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).
651No argument may receive a value more than once.
652Here's an example that fails due to this restriction::
Georg Brandl116aa622007-08-15 14:28:22 +0000653
654 >>> def function(a):
655 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +0000656 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000657 >>> function(0, a=0)
658 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530659 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000660 TypeError: function() got multiple values for keyword argument 'a'
661
662When a final formal parameter of the form ``**name`` is present, it receives a
663dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
664those corresponding to a formal parameter. This may be combined with a formal
665parameter of the form ``*name`` (described in the next subsection) which
Julien Palard51ddab82019-05-28 15:10:23 +0200666receives a :ref:`tuple <tut-tuples>` containing the positional
667arguments beyond the formal parameter list. (``*name`` must occur
668before ``**name``.) For example, if we define a function like this::
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670 def cheeseshop(kind, *arguments, **keywords):
Georg Brandl5d955ed2008-09-13 17:18:21 +0000671 print("-- Do you have any", kind, "?")
Guido van Rossum0616b792007-08-31 03:25:11 +0000672 print("-- I'm sorry, we're all out of", kind)
Georg Brandl70543ac2010-10-15 15:32:05 +0000673 for arg in arguments:
674 print(arg)
Georg Brandl5d955ed2008-09-13 17:18:21 +0000675 print("-" * 40)
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200676 for kw in keywords:
Georg Brandl70543ac2010-10-15 15:32:05 +0000677 print(kw, ":", keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679It could be called like this::
680
Georg Brandl5d955ed2008-09-13 17:18:21 +0000681 cheeseshop("Limburger", "It's very runny, sir.",
Georg Brandl116aa622007-08-15 14:28:22 +0000682 "It's really very, VERY runny, sir.",
Georg Brandl5d955ed2008-09-13 17:18:21 +0000683 shopkeeper="Michael Palin",
684 client="John Cleese",
685 sketch="Cheese Shop Sketch")
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Martin Panter1050d2d2016-07-26 11:18:21 +0200687and of course it would print:
688
689.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691 -- Do you have any Limburger ?
692 -- I'm sorry, we're all out of Limburger
693 It's very runny, sir.
694 It's really very, VERY runny, sir.
695 ----------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000696 shopkeeper : Michael Palin
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200697 client : John Cleese
Georg Brandl116aa622007-08-15 14:28:22 +0000698 sketch : Cheese Shop Sketch
699
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200700Note that the order in which the keyword arguments are printed is guaranteed
701to match the order in which they were provided in the function call.
702
Pablo Galindob76302d2019-05-29 00:45:32 +0100703Special parameters
704------------------
705
706By default, arguments may be passed to a Python function either by position
707or explicitly by keyword. For readability and performance, it makes sense to
708restrict the way arguments can be passed so that a developer need only look
709at the function definition to determine if items are passed by position, by
710position or keyword, or by keyword.
711
712A function definition may look like:
713
714.. code-block:: none
715
716 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
717 ----------- ---------- ----------
718 | | |
719 | Positional or keyword |
720 | - Keyword only
721 -- Positional only
722
723where ``/`` and ``*`` are optional. If used, these symbols indicate the kind of
724parameter by how the arguments may be passed to the function:
725positional-only, positional-or-keyword, and keyword-only. Keyword parameters
726are also referred to as named parameters.
727
728-------------------------------
729Positional-or-Keyword Arguments
730-------------------------------
731
732If ``/`` and ``*`` are not present in the function definition, arguments may
733be passed to a function by position or by keyword.
734
735--------------------------
736Positional-Only Parameters
737--------------------------
738
739Looking at this in a bit more detail, it is possible to mark certain parameters
740as *positional-only*. If *positional-only*, the parameters' order matters, and
741the parameters cannot be passed by keyword. Positional-only parameters are
742placed before a ``/`` (forward-slash). The ``/`` is used to logically
743separate the positional-only parameters from the rest of the parameters.
744If there is no ``/`` in the function definition, there are no positional-only
745parameters.
746
747Parameters following the ``/`` may be *positional-or-keyword* or *keyword-only*.
748
749----------------------
750Keyword-Only Arguments
751----------------------
752
753To mark parameters as *keyword-only*, indicating the parameters must be passed
754by keyword argument, place an ``*`` in the arguments list just before the first
755*keyword-only* parameter.
756
757-----------------
758Function Examples
759-----------------
760
761Consider the following example function definitions paying close attention to the
762markers ``/`` and ``*``::
763
764 >>> def standard_arg(arg):
765 ... print(arg)
766 ...
767 >>> def pos_only_arg(arg, /):
768 ... print(arg)
769 ...
770 >>> def kwd_only_arg(*, arg):
771 ... print(arg)
772 ...
773 >>> def combined_example(pos_only, /, standard, *, kwd_only):
774 ... print(pos_only, standard, kwd_only)
775
776
777The first function definition, ``standard_arg``, the most familiar form,
778places no restrictions on the calling convention and arguments may be
779passed by position or keyword::
780
781 >>> standard_arg(2)
782 2
783
784 >>> standard_arg(arg=2)
785 2
786
787The second function ``pos_only_arg`` is restricted to only use positional
788parameters as there is a ``/`` in the function definition::
789
790 >>> pos_only_arg(1)
791 1
792
793 >>> pos_only_arg(arg=1)
794 Traceback (most recent call last):
795 File "<stdin>", line 1, in <module>
796 TypeError: pos_only_arg() got an unexpected keyword argument 'arg'
797
798The third function ``kwd_only_args`` only allows keyword arguments as indicated
799by a ``*`` in the function definition::
800
801 >>> kwd_only_arg(3)
802 Traceback (most recent call last):
803 File "<stdin>", line 1, in <module>
804 TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given
805
806 >>> kwd_only_arg(arg=3)
807 3
808
809And the last uses all three calling conventions in the same function
810definition::
811
812 >>> combined_example(1, 2, 3)
813 Traceback (most recent call last):
814 File "<stdin>", line 1, in <module>
815 TypeError: combined_example() takes 2 positional arguments but 3 were given
816
817 >>> combined_example(1, 2, kwd_only=3)
818 1 2 3
819
820 >>> combined_example(1, standard=2, kwd_only=3)
821 1 2 3
822
823 >>> combined_example(pos_only=1, standard=2, kwd_only=3)
824 Traceback (most recent call last):
825 File "<stdin>", line 1, in <module>
826 TypeError: combined_example() got an unexpected keyword argument 'pos_only'
827
828
829Finally, consider this function definition which has a potential collision between the positional argument ``name`` and ``**kwds`` which has ``name`` as a key::
830
831 def foo(name, **kwds):
832 return 'name' in kwds
833
834There is no possible call that will make it return ``True`` as the keyword ``'name'``
Denis Ovsienko0be7c212020-08-19 12:29:47 +0100835will always bind to the first parameter. For example::
Pablo Galindob76302d2019-05-29 00:45:32 +0100836
837 >>> foo(1, **{'name': 2})
838 Traceback (most recent call last):
839 File "<stdin>", line 1, in <module>
840 TypeError: foo() got multiple values for argument 'name'
841 >>>
842
843But using ``/`` (positional only arguments), it is possible since it allows ``name`` as a positional argument and ``'name'`` as a key in the keyword arguments::
844
845 def foo(name, /, **kwds):
846 return 'name' in kwds
847 >>> foo(1, **{'name': 2})
848 True
849
850In other words, the names of positional-only parameters can be used in
851``**kwds`` without ambiguity.
852
853-----
854Recap
855-----
856
857The use case will determine which parameters to use in the function definition::
858
859 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
860
861As guidance:
862
863* Use positional-only if you want the name of the parameters to not be
864 available to the user. This is useful when parameter names have no real
865 meaning, if you want to enforce the order of the arguments when the function
866 is called or if you need to take some positional parameters and arbitrary
867 keywords.
868* Use keyword-only when names have meaning and the function definition is
869 more understandable by being explicit with names or you want to prevent
870 users relying on the position of the argument being passed.
Adorilson Bezerrab7af4e72019-09-16 04:04:58 -0300871* For an API, use positional-only to prevent breaking API changes
Pablo Galindob76302d2019-05-29 00:45:32 +0100872 if the parameter's name is modified in the future.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874.. _tut-arbitraryargs:
875
876Arbitrary Argument Lists
877------------------------
878
Christian Heimesdae2a892008-04-19 00:55:37 +0000879.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200880 single: * (asterisk); in function calls
Christian Heimesdae2a892008-04-19 00:55:37 +0000881
Georg Brandl116aa622007-08-15 14:28:22 +0000882Finally, the least frequently used option is to specify that a function can be
883called with an arbitrary number of arguments. These arguments will be wrapped
Georg Brandl5d955ed2008-09-13 17:18:21 +0000884up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
885zero or more normal arguments may occur. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000886
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000887 def write_multiple_items(file, separator, *args):
888 file.write(separator.join(args))
Georg Brandl116aa622007-08-15 14:28:22 +0000889
Georg Brandl48310cd2009-01-03 21:18:54 +0000890
Guido van Rossum0616b792007-08-31 03:25:11 +0000891Normally, these ``variadic`` arguments will be last in the list of formal
Georg Brandl48310cd2009-01-03 21:18:54 +0000892parameters, because they scoop up all remaining input arguments that are
Guido van Rossum0616b792007-08-31 03:25:11 +0000893passed to the function. Any formal parameters which occur after the ``*args``
Georg Brandl48310cd2009-01-03 21:18:54 +0000894parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000895keywords rather than positional arguments. ::
Georg Brandl48310cd2009-01-03 21:18:54 +0000896
Guido van Rossum0616b792007-08-31 03:25:11 +0000897 >>> def concat(*args, sep="/"):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300898 ... return sep.join(args)
Guido van Rossum0616b792007-08-31 03:25:11 +0000899 ...
900 >>> concat("earth", "mars", "venus")
901 'earth/mars/venus'
902 >>> concat("earth", "mars", "venus", sep=".")
903 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000904
905.. _tut-unpacking-arguments:
906
907Unpacking Argument Lists
908------------------------
909
910The reverse situation occurs when the arguments are already in a list or tuple
911but need to be unpacked for a function call requiring separate positional
912arguments. For instance, the built-in :func:`range` function expects separate
913*start* and *stop* arguments. If they are not available separately, write the
Raymond Hettingerfb28fcc2019-03-27 21:03:02 -0700914function call with the ``*``\ -operator to unpack the arguments out of a list
Georg Brandl116aa622007-08-15 14:28:22 +0000915or tuple::
916
Guido van Rossum0616b792007-08-31 03:25:11 +0000917 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000918 [3, 4, 5]
919 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000920 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000921 [3, 4, 5]
922
Christian Heimesdae2a892008-04-19 00:55:37 +0000923.. index::
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300924 single: **; in function calls
Christian Heimesdae2a892008-04-19 00:55:37 +0000925
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200926In the same fashion, dictionaries can deliver keyword arguments with the
Raymond Hettingerfb28fcc2019-03-27 21:03:02 -0700927``**``\ -operator::
Georg Brandl116aa622007-08-15 14:28:22 +0000928
929 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000930 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000931 ... print("if you put", voltage, "volts through it.", end=' ')
932 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000933 ...
934 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
935 >>> parrot(**d)
936 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
937
938
939.. _tut-lambda:
940
Georg Brandlde5aff12013-10-06 10:22:45 +0200941Lambda Expressions
942------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000943
Georg Brandlde5aff12013-10-06 10:22:45 +0200944Small anonymous functions can be created with the :keyword:`lambda` keyword.
945This function returns the sum of its two arguments: ``lambda a, b: a+b``.
Georg Brandl242e6a02013-10-06 10:28:39 +0200946Lambda functions can be used wherever function objects are required. They are
Georg Brandlde5aff12013-10-06 10:22:45 +0200947syntactically restricted to a single expression. Semantically, they are just
948syntactic sugar for a normal function definition. Like nested function
949definitions, lambda functions can reference variables from the containing
950scope::
Georg Brandl116aa622007-08-15 14:28:22 +0000951
952 >>> def make_incrementor(n):
953 ... return lambda x: x + n
954 ...
955 >>> f = make_incrementor(42)
956 >>> f(0)
957 42
958 >>> f(1)
959 43
960
Georg Brandlde5aff12013-10-06 10:22:45 +0200961The above example uses a lambda expression to return a function. Another use
962is to pass a small function as an argument::
963
964 >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
965 >>> pairs.sort(key=lambda pair: pair[1])
966 >>> pairs
967 [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
968
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970.. _tut-docstrings:
971
972Documentation Strings
973---------------------
974
975.. index::
976 single: docstrings
977 single: documentation strings
978 single: strings, documentation
979
Guido van Rossum0616b792007-08-31 03:25:11 +0000980Here are some conventions about the content and formatting of documentation
Georg Brandl48310cd2009-01-03 21:18:54 +0000981strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000982
983The first line should always be a short, concise summary of the object's
984purpose. For brevity, it should not explicitly state the object's name or type,
985since these are available by other means (except if the name happens to be a
986verb describing a function's operation). This line should begin with a capital
987letter and end with a period.
988
989If there are more lines in the documentation string, the second line should be
990blank, visually separating the summary from the rest of the description. The
991following lines should be one or more paragraphs describing the object's calling
992conventions, its side effects, etc.
993
994The Python parser does not strip indentation from multi-line string literals in
995Python, so tools that process documentation have to strip indentation if
996desired. This is done using the following convention. The first non-blank line
997*after* the first line of the string determines the amount of indentation for
998the entire documentation string. (We can't use the first line since it is
999generally adjacent to the string's opening quotes so its indentation is not
1000apparent in the string literal.) Whitespace "equivalent" to this indentation is
1001then stripped from the start of all lines of the string. Lines that are
1002indented less should not occur, but if they occur all their leading whitespace
1003should be stripped. Equivalence of whitespace should be tested after expansion
1004of tabs (to 8 spaces, normally).
1005
1006Here is an example of a multi-line docstring::
1007
1008 >>> def my_function():
1009 ... """Do nothing, but document it.
Georg Brandl48310cd2009-01-03 21:18:54 +00001010 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001011 ... No, really, it doesn't do anything.
1012 ... """
1013 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +00001014 ...
Guido van Rossum0616b792007-08-31 03:25:11 +00001015 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +00001016 Do nothing, but document it.
1017
1018 No, really, it doesn't do anything.
1019
1020
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001021.. _tut-annotations:
1022
1023Function Annotations
1024--------------------
1025
1026.. sectionauthor:: Zachary Ware <zachary.ware@gmail.com>
1027.. index::
1028 pair: function; annotations
Serhiy Storchakaddb961d2018-10-26 09:00:49 +03001029 single: ->; function annotations
Serhiy Storchaka913876d2018-10-28 13:41:26 +02001030 single: : (colon); function annotations
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001031
Zachary Waref3b990e2015-04-13 11:30:47 -05001032:ref:`Function annotations <function>` are completely optional metadata
Neeraj Badlani643ff712018-04-25 10:52:13 -07001033information about the types used by user-defined functions (see :pep:`3107` and
1034:pep:`484` for more information).
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001035
Cheryl Sabellab7105c92018-12-24 00:09:09 -05001036:term:`Annotations <function annotation>` are stored in the :attr:`__annotations__`
1037attribute of the function as a dictionary and have no effect on any other part of the
1038function. Parameter annotations are defined by a colon after the parameter name, followed
1039by an expression evaluating to the value of the annotation. Return annotations are
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001040defined by a literal ``->``, followed by an expression, between the parameter
1041list and the colon denoting the end of the :keyword:`def` statement. The
Irit Katriela53e9a72021-03-27 17:20:58 +00001042following example has a required argument, an optional argument, and the return
Zachary Waref3b990e2015-04-13 11:30:47 -05001043value annotated::
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001044
Zachary Waref3b990e2015-04-13 11:30:47 -05001045 >>> def f(ham: str, eggs: str = 'eggs') -> str:
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001046 ... print("Annotations:", f.__annotations__)
1047 ... print("Arguments:", ham, eggs)
Zachary Waref3b990e2015-04-13 11:30:47 -05001048 ... return ham + ' and ' + eggs
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001049 ...
Zachary Waref3b990e2015-04-13 11:30:47 -05001050 >>> f('spam')
1051 Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
1052 Arguments: spam eggs
1053 'spam and eggs'
Andrew Svetlov1491cbd2012-11-01 21:26:55 +02001054
Christian Heimes043d6f62008-01-07 17:19:16 +00001055.. _tut-codingstyle:
1056
1057Intermezzo: Coding Style
1058========================
1059
1060.. sectionauthor:: Georg Brandl <georg@python.org>
1061.. index:: pair: coding; style
1062
1063Now that you are about to write longer, more complex pieces of Python, it is a
1064good time to talk about *coding style*. Most languages can be written (or more
1065concise, *formatted*) in different styles; some are more readable than others.
1066Making it easy for others to read your code is always a good idea, and adopting
1067a nice coding style helps tremendously for that.
1068
Christian Heimesdae2a892008-04-19 00:55:37 +00001069For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Christian Heimes043d6f62008-01-07 17:19:16 +00001070it promotes a very readable and eye-pleasing coding style. Every Python
1071developer should read it at some point; here are the most important points
1072extracted for you:
1073
1074* Use 4-space indentation, and no tabs.
1075
1076 4 spaces are a good compromise between small indentation (allows greater
1077 nesting depth) and large indentation (easier to read). Tabs introduce
1078 confusion, and are best left out.
1079
1080* Wrap lines so that they don't exceed 79 characters.
1081
1082 This helps users with small displays and makes it possible to have several
1083 code files side-by-side on larger displays.
1084
1085* Use blank lines to separate functions and classes, and larger blocks of
1086 code inside functions.
1087
1088* When possible, put comments on a line of their own.
1089
1090* Use docstrings.
1091
1092* Use spaces around operators and after commas, but not directly inside
1093 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
1094
1095* Name your classes and functions consistently; the convention is to use
Julien Palard2da622f2019-07-08 23:06:32 +02001096 ``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for functions
Georg Brandl5d955ed2008-09-13 17:18:21 +00001097 and methods. Always use ``self`` as the name for the first method argument
1098 (see :ref:`tut-firstclasses` for more on classes and methods).
Christian Heimes043d6f62008-01-07 17:19:16 +00001099
1100* Don't use fancy encodings if your code is meant to be used in international
Georg Brandl7ae90dd2009-06-08 18:59:09 +00001101 environments. Python's default, UTF-8, or even plain ASCII work best in any
1102 case.
1103
1104* Likewise, don't use non-ASCII characters in identifiers if there is only the
1105 slightest chance people speaking a different language will read or maintain
1106 the code.
Christian Heimes043d6f62008-01-07 17:19:16 +00001107
Georg Brandl116aa622007-08-15 14:28:22 +00001108
1109.. rubric:: Footnotes
1110
Christian Heimes043d6f62008-01-07 17:19:16 +00001111.. [#] Actually, *call by object reference* would be a better description,
1112 since if a mutable object is passed, the caller will see any changes the
1113 callee makes to it (items inserted into a list).