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