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