Debian Codegraph @

Doc/tutorial/controlflow.rst

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