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