blob: 9ee18f75847e7bdc28a9e85b975c4e31098710aa [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-morecontrol:
2
3***********************
4More Control Flow Tools
5***********************
6
Diego Alberto Barriga Martínezb5748132019-09-17 11:57:55 -05007Besides the :keyword:`while` statement just introduced, Python uses the usual
8flow control statements known from other languages, with some twists.
Georg Brandl116aa622007-08-15 14:28:22 +00009
10
11.. _tut-if:
12
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020013:keyword:`!if` Statements
14=========================
Georg Brandl116aa622007-08-15 14:28:22 +000015
16Perhaps the most well-known statement type is the :keyword:`if` statement. For
17example::
18
Georg Brandle9af2842007-08-17 05:54:09 +000019 >>> x = int(input("Please enter an integer: "))
Georg Brandl5d955ed2008-09-13 17:18:21 +000020 Please enter an integer: 42
Georg Brandl116aa622007-08-15 14:28:22 +000021 >>> if x < 0:
Ezio Melottie65cb192013-11-17 22:07:48 +020022 ... x = 0
23 ... print('Negative changed to zero')
Georg Brandl116aa622007-08-15 14:28:22 +000024 ... elif x == 0:
Ezio Melottie65cb192013-11-17 22:07:48 +020025 ... print('Zero')
Georg Brandl116aa622007-08-15 14:28:22 +000026 ... elif x == 1:
Ezio Melottie65cb192013-11-17 22:07:48 +020027 ... print('Single')
Georg Brandl116aa622007-08-15 14:28:22 +000028 ... else:
Ezio Melottie65cb192013-11-17 22:07:48 +020029 ... print('More')
Georg Brandl5d955ed2008-09-13 17:18:21 +000030 ...
31 More
Georg Brandl116aa622007-08-15 14:28:22 +000032
33There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020034optional. The keyword ':keyword:`!elif`' is short for 'else if', and is useful
35to avoid excessive indentation. An :keyword:`!if` ... :keyword:`!elif` ...
36:keyword:`!elif` ... sequence is a substitute for the ``switch`` or
Christian Heimes5b5e81c2007-12-31 16:14:33 +000037``case`` statements found in other languages.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39
40.. _tut-for:
41
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020042:keyword:`!for` Statements
43==========================
Georg Brandl116aa622007-08-15 14:28:22 +000044
45.. index::
46 statement: for
Georg Brandl116aa622007-08-15 14:28:22 +000047
48The :keyword:`for` statement in Python differs a bit from what you may be used
49to in C or Pascal. Rather than always iterating over an arithmetic progression
50of numbers (like in Pascal), or giving the user the ability to define both the
Serhiy Storchaka2b57c432018-12-19 08:09:46 +020051iteration step and halting condition (as C), Python's :keyword:`!for` statement
Georg Brandl116aa622007-08-15 14:28:22 +000052iterates over the items of any sequence (a list or a string), in the order that
53they appear in the sequence. For example (no pun intended):
54
Christian Heimes5b5e81c2007-12-31 16:14:33 +000055.. One suggestion was to give a real C example here, but that may only serve to
56 confuse non-C programmers.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58::
59
60 >>> # Measure some strings:
Chris Jerdonek4fab8f02012-10-15 19:44:47 -070061 ... words = ['cat', 'window', 'defenestrate']
62 >>> for w in words:
63 ... print(w, len(w))
Georg Brandl48310cd2009-01-03 21:18:54 +000064 ...
Georg Brandl116aa622007-08-15 14:28:22 +000065 cat 3
66 window 6
67 defenestrate 12
68
Raymond Hettinger6fcb6cf2019-08-22 23:44:19 -070069Code that modifies a collection while iterating over that same collection can
70be tricky to get right. Instead, it is usually more straight-forward to loop
71over a copy of the collection or to create a new collection::
Georg Brandl116aa622007-08-15 14:28:22 +000072
Antoine6fad3e62020-05-23 02:29:34 +020073 # Create a sample collection
74 users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
75
Raymond Hettinger6fcb6cf2019-08-22 23:44:19 -070076 # Strategy: Iterate over a copy
77 for user, status in users.copy().items():
78 if status == 'inactive':
79 del users[user]
Georg Brandl116aa622007-08-15 14:28:22 +000080
Raymond Hettinger6fcb6cf2019-08-22 23:44:19 -070081 # Strategy: Create a new collection
82 active_users = {}
83 for user, status in users.items():
84 if status == 'active':
85 active_users[user] = status
Georg Brandl40383c82016-02-15 17:50:33 +010086
Georg Brandl116aa622007-08-15 14:28:22 +000087
88.. _tut-range:
89
90The :func:`range` Function
91==========================
92
93If you do need to iterate over a sequence of numbers, the built-in function
Guido van Rossum0616b792007-08-31 03:25:11 +000094:func:`range` comes in handy. It generates arithmetic progressions::
Georg Brandl116aa622007-08-15 14:28:22 +000095
Guido van Rossum0616b792007-08-31 03:25:11 +000096 >>> for i in range(5):
97 ... print(i)
98 ...
99 0
100 1
101 2
102 3
103 4
Georg Brandl48310cd2009-01-03 21:18:54 +0000104
Georg Brandl7d821062010-06-27 10:59:19 +0000105The given end point is never part of the generated sequence; ``range(10)`` generates
Guido van Rossum0616b792007-08-31 03:25:11 +000010610 values, the legal indices for items of a sequence of length 10. It
Georg Brandl116aa622007-08-15 14:28:22 +0000107is possible to let the range start at another number, or to specify a different
108increment (even negative; sometimes this is called the 'step')::
109
Georg Brandl48310cd2009-01-03 21:18:54 +0000110 range(5, 10)
Steven M. Vascellaro83d70622018-03-09 14:57:21 -0500111 5, 6, 7, 8, 9
Guido van Rossum0616b792007-08-31 03:25:11 +0000112
Georg Brandl48310cd2009-01-03 21:18:54 +0000113 range(0, 10, 3)
Guido van Rossum0616b792007-08-31 03:25:11 +0000114 0, 3, 6, 9
115
Georg Brandl48310cd2009-01-03 21:18:54 +0000116 range(-10, -100, -30)
Guido van Rossum0616b792007-08-31 03:25:11 +0000117 -10, -40, -70
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Georg Brandlaf265f42008-12-07 15:06:20 +0000119To iterate over the indices of a sequence, you can combine :func:`range` and
120:func:`len` as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
123 >>> for i in range(len(a)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000124 ... print(i, a[i])
Georg Brandl48310cd2009-01-03 21:18:54 +0000125 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000126 0 Mary
127 1 had
128 2 a
129 3 little
130 4 lamb
131
Georg Brandlaf265f42008-12-07 15:06:20 +0000132In most such cases, however, it is convenient to use the :func:`enumerate`
133function, see :ref:`tut-loopidioms`.
134
Guido van Rossum0616b792007-08-31 03:25:11 +0000135A strange thing happens if you just print a range::
136
137 >>> print(range(10))
138 range(0, 10)
139
140In many ways the object returned by :func:`range` behaves as if it is a list,
Georg Brandl48310cd2009-01-03 21:18:54 +0000141but in fact it isn't. It is an object which returns the successive items of
142the desired sequence when you iterate over it, but it doesn't really make
143the list, thus saving space.
Guido van Rossum0616b792007-08-31 03:25:11 +0000144
Marco Buttu218e47b2019-06-01 23:11:48 +0200145We say such an object is :term:`iterable`, that is, suitable as a target for
Georg Brandl48310cd2009-01-03 21:18:54 +0000146functions and constructs that expect something from which they can
Marco Buttu218e47b2019-06-01 23:11:48 +0200147obtain successive items until the supply is exhausted. We have seen that
Don Kirkby3ed4d252020-02-09 16:57:46 -0800148the :keyword:`for` statement is such a construct, while an example of a function
Marco Buttu218e47b2019-06-01 23:11:48 +0200149that takes an iterable is :func:`sum`::
Guido van Rossum0616b792007-08-31 03:25:11 +0000150
Marco Buttu218e47b2019-06-01 23:11:48 +0200151 >>> sum(range(4)) # 0 + 1 + 2 + 3
152 6
Guido van Rossum0616b792007-08-31 03:25:11 +0000153
Marco Buttu218e47b2019-06-01 23:11:48 +0200154Later we will see more functions that return iterables and take iterables as
155arguments. Lastly, maybe you are curious about how to get a list from a range.
156Here is the solution::
Guido van Rossum0616b792007-08-31 03:25:11 +0000157
Marco Buttu218e47b2019-06-01 23:11:48 +0200158 >>> list(range(4))
159 [0, 1, 2, 3]
Georg Brandl116aa622007-08-15 14:28:22 +0000160
Marco Buttu218e47b2019-06-01 23:11:48 +0200161In chapter :ref:`tut-structures`, we will discuss in more detail about
162:func:`list`.
Georg Brandlaf265f42008-12-07 15:06:20 +0000163
Georg Brandl116aa622007-08-15 14:28:22 +0000164.. _tut-break:
165
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200166:keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` Clauses on Loops
167============================================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000168
regexaurus36fc8962017-06-27 18:40:41 -0400169The :keyword:`break` statement, like in C, breaks out of the innermost enclosing
Georg Brandl116aa622007-08-15 14:28:22 +0000170:keyword:`for` or :keyword:`while` loop.
171
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200172Loop statements may have an :keyword:`!else` clause; it is executed when the loop
Marco Buttu218e47b2019-06-01 23:11:48 +0200173terminates through exhaustion of the iterable (with :keyword:`for`) or when the
Georg Brandl116aa622007-08-15 14:28:22 +0000174condition becomes false (with :keyword:`while`), but not when the loop is
175terminated by a :keyword:`break` statement. This is exemplified by the
176following loop, which searches for prime numbers::
177
178 >>> for n in range(2, 10):
179 ... for x in range(2, n):
180 ... if n % x == 0:
Georg Brandlb03c1d92008-05-01 18:06:50 +0000181 ... print(n, 'equals', x, '*', n//x)
Georg Brandl116aa622007-08-15 14:28:22 +0000182 ... break
183 ... else:
184 ... # loop fell through without finding a factor
Guido van Rossum0616b792007-08-31 03:25:11 +0000185 ... print(n, 'is a prime number')
Georg Brandl48310cd2009-01-03 21:18:54 +0000186 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000187 2 is a prime number
188 3 is a prime number
189 4 equals 2 * 2
190 5 is a prime number
191 6 equals 2 * 3
192 7 is a prime number
193 8 equals 2 * 4
194 9 equals 3 * 3
195
Georg Brandlbdbdfb12011-08-08 21:45:13 +0200196(Yes, this is the correct code. Look closely: the ``else`` clause belongs to
197the :keyword:`for` loop, **not** the :keyword:`if` statement.)
198
Nick Coghlana3a164a2012-06-07 22:41:34 +1000199When used with a loop, the ``else`` clause has more in common with the
Marco Buttu218e47b2019-06-01 23:11:48 +0200200``else`` clause of a :keyword:`try` statement than it does with that of
201:keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs
Nick Coghlana3a164a2012-06-07 22:41:34 +1000202when no exception occurs, and a loop's ``else`` clause runs when no ``break``
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200203occurs. For more on the :keyword:`!try` statement and exceptions, see
Nick Coghlana3a164a2012-06-07 22:41:34 +1000204:ref:`tut-handling`.
205
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700206The :keyword:`continue` statement, also borrowed from C, continues with the next
207iteration of the loop::
208
209 >>> for num in range(2, 10):
Eli Bendersky31a11902012-08-18 09:50:09 +0300210 ... if num % 2 == 0:
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700211 ... print("Found an even number", num)
212 ... continue
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400213 ... print("Found an odd number", num)
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700214 Found an even number 2
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400215 Found an odd number 3
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700216 Found an even number 4
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400217 Found an odd number 5
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700218 Found an even number 6
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400219 Found an odd number 7
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700220 Found an even number 8
Neeraj Samtani7bcc6452020-09-15 17:39:29 +0400221 Found an odd number 9
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. _tut-pass:
224
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200225:keyword:`!pass` Statements
226===========================
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228The :keyword:`pass` statement does nothing. It can be used when a statement is
229required syntactically but the program requires no action. For example::
230
231 >>> while True:
Georg Brandl5d955ed2008-09-13 17:18:21 +0000232 ... pass # Busy-wait for keyboard interrupt (Ctrl+C)
Georg Brandl48310cd2009-01-03 21:18:54 +0000233 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Benjamin Peterson92035012008-12-27 16:00:54 +0000235This is commonly used for creating minimal classes::
Georg Brandla971c652008-11-07 09:39:56 +0000236
Benjamin Peterson92035012008-12-27 16:00:54 +0000237 >>> class MyEmptyClass:
Georg Brandla971c652008-11-07 09:39:56 +0000238 ... pass
Benjamin Peterson92035012008-12-27 16:00:54 +0000239 ...
Georg Brandla971c652008-11-07 09:39:56 +0000240
241Another place :keyword:`pass` can be used is as a place-holder for a function or
Benjamin Peterson92035012008-12-27 16:00:54 +0000242conditional body when you are working on new code, allowing you to keep thinking
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200243at a more abstract level. The :keyword:`!pass` is silently ignored::
Georg Brandla971c652008-11-07 09:39:56 +0000244
245 >>> def initlog(*args):
Benjamin Peterson92035012008-12-27 16:00:54 +0000246 ... pass # Remember to implement this!
Georg Brandl48310cd2009-01-03 21:18:54 +0000247 ...
Georg Brandla971c652008-11-07 09:39:56 +0000248
Georg Brandl116aa622007-08-15 14:28:22 +0000249.. _tut-functions:
250
251Defining Functions
252==================
253
254We can create a function that writes the Fibonacci series to an arbitrary
255boundary::
256
257 >>> def fib(n): # write Fibonacci series up to n
258 ... """Print a Fibonacci series up to n."""
259 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000260 ... while a < n:
261 ... print(a, end=' ')
Georg Brandl116aa622007-08-15 14:28:22 +0000262 ... a, b = b, a+b
Guido van Rossum0616b792007-08-31 03:25:11 +0000263 ... print()
Georg Brandl48310cd2009-01-03 21:18:54 +0000264 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000265 >>> # Now call the function we just defined:
266 ... fib(2000)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000267 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269.. index::
270 single: documentation strings
271 single: docstrings
272 single: strings, documentation
273
274The keyword :keyword:`def` introduces a function *definition*. It must be
275followed by the function name and the parenthesized list of formal parameters.
276The statements that form the body of the function start at the next line, and
Georg Brandl5d955ed2008-09-13 17:18:21 +0000277must be indented.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Georg Brandl5d955ed2008-09-13 17:18:21 +0000279The first statement of the function body can optionally be a string literal;
280this string literal is the function's documentation string, or :dfn:`docstring`.
281(More about docstrings can be found in the section :ref:`tut-docstrings`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000282There are tools which use docstrings to automatically produce online or printed
283documentation, or to let the user interactively browse through code; it's good
Georg Brandl5d955ed2008-09-13 17:18:21 +0000284practice to include docstrings in code that you write, so make a habit of it.
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286The *execution* of a function introduces a new symbol table used for the local
287variables of the function. More precisely, all variable assignments in a
288function store the value in the local symbol table; whereas variable references
Georg Brandl86def6c2008-01-21 20:36:10 +0000289first look in the local symbol table, then in the local symbol tables of
290enclosing functions, then in the global symbol table, and finally in the table
pbhde1f95e72019-05-29 05:38:03 +0200291of built-in names. Thus, global variables and variables of enclosing functions
292cannot be directly assigned a value within a function (unless, for global
293variables, named in a :keyword:`global` statement, or, for variables of enclosing
294functions, named in a :keyword:`nonlocal` statement), although they may be
295referenced.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297The actual parameters (arguments) to a function call are introduced in the local
298symbol table of the called function when it is called; thus, arguments are
299passed using *call by value* (where the *value* is always an object *reference*,
Terry Jan Reedyb30fcba2021-02-19 19:26:21 -0500300not the value of the object). [#]_ When a function calls another function,
301or calls itself recursively, a new
Georg Brandl116aa622007-08-15 14:28:22 +0000302local symbol table is created for that call.
303
Joannah Nanjekyed12af712020-07-05 22:47:15 -0300304A function definition associates the function name with the function object in
305the current symbol table. The interpreter recognizes the object pointed to by
306that name as a user-defined function. Other names can also point to that same
307function object and can also be used to access the function::
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309 >>> fib
310 <function fib at 10042ed0>
311 >>> f = fib
312 >>> f(100)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000313 0 1 1 2 3 5 8 13 21 34 55 89
Georg Brandl116aa622007-08-15 14:28:22 +0000314
Georg Brandl5d955ed2008-09-13 17:18:21 +0000315Coming from other languages, you might object that ``fib`` is not a function but
316a procedure since it doesn't return a value. In fact, even functions without a
317:keyword:`return` statement do return a value, albeit a rather boring one. This
318value is called ``None`` (it's a built-in name). Writing the value ``None`` is
319normally suppressed by the interpreter if it would be the only value written.
320You can see it if you really want to using :func:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000321
Georg Brandl9afde1c2007-11-01 20:32:30 +0000322 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000323 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000324 None
325
326It is simple to write a function that returns a list of the numbers of the
327Fibonacci series, instead of printing it::
328
Serhiy Storchakadba90392016-05-10 12:01:23 +0300329 >>> def fib2(n): # return Fibonacci series up to n
Georg Brandl116aa622007-08-15 14:28:22 +0000330 ... """Return a list containing the Fibonacci series up to n."""
331 ... result = []
332 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000333 ... while a < n:
334 ... result.append(a) # see below
Georg Brandl116aa622007-08-15 14:28:22 +0000335 ... a, b = b, a+b
336 ... return result
Georg Brandl48310cd2009-01-03 21:18:54 +0000337 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000338 >>> f100 = fib2(100) # call it
339 >>> f100 # write the result
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000340 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342This example, as usual, demonstrates some new Python features:
343
344* The :keyword:`return` statement returns with a value from a function.
Serhiy Storchaka2b57c432018-12-19 08:09:46 +0200345 :keyword:`!return` without an expression argument returns ``None``. Falling off
Georg Brandl5d955ed2008-09-13 17:18:21 +0000346 the end of a function also returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000348* The statement ``result.append(a)`` calls a *method* of the list object
Georg Brandl116aa622007-08-15 14:28:22 +0000349 ``result``. A method is a function that 'belongs' to an object and is named
350 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
351 and ``methodname`` is the name of a method that is defined by the object's type.
352 Different types define different methods. Methods of different types may have
353 the same name without causing ambiguity. (It is possible to define your own
Georg Brandlc6c31782009-06-08 13:41:29 +0000354 object types and methods, using *classes*, see :ref:`tut-classes`)
Georg Brandl116aa622007-08-15 14:28:22 +0000355 The method :meth:`append` shown in the example is defined for list objects; it
356 adds a new element at the end of the list. In this example it is equivalent to
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000357 ``result = result + [a]``, but more efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359
360.. _tut-defining:
361
362More on Defining Functions
363==========================
364
365It is also possible to define functions with a variable number of arguments.
366There are three forms, which can be combined.
367
368
369.. _tut-defaultargs:
370
371Default Argument Values
372-----------------------
373
374The most useful form is to specify a default value for one or more arguments.
375This creates a function that can be called with fewer arguments than it is
376defined to allow. For example::
377
Berker Peksag0a5120e2016-06-02 11:31:19 -0700378 def ask_ok(prompt, retries=4, reminder='Please try again!'):
Georg Brandl116aa622007-08-15 14:28:22 +0000379 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000380 ok = input(prompt)
Georg Brandlc6c31782009-06-08 13:41:29 +0000381 if ok in ('y', 'ye', 'yes'):
382 return True
383 if ok in ('n', 'no', 'nop', 'nope'):
384 return False
Georg Brandl116aa622007-08-15 14:28:22 +0000385 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000386 if retries < 0:
Berker Peksag0a5120e2016-06-02 11:31:19 -0700387 raise ValueError('invalid user response')
388 print(reminder)
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Georg Brandlc6c31782009-06-08 13:41:29 +0000390This function can be called in several ways:
391
392* giving only the mandatory argument:
393 ``ask_ok('Do you really want to quit?')``
394* giving one of the optional arguments:
395 ``ask_ok('OK to overwrite the file?', 2)``
396* or even giving all arguments:
397 ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399This example also introduces the :keyword:`in` keyword. This tests whether or
400not a sequence contains a certain value.
401
402The default values are evaluated at the point of function definition in the
403*defining* scope, so that ::
404
405 i = 5
406
407 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000408 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410 i = 6
411 f()
412
413will print ``5``.
414
415**Important warning:** The default value is evaluated only once. This makes a
416difference when the default is a mutable object such as a list, dictionary, or
417instances of most classes. For example, the following function accumulates the
418arguments passed to it on subsequent calls::
419
420 def f(a, L=[]):
421 L.append(a)
422 return L
423
Guido van Rossum0616b792007-08-31 03:25:11 +0000424 print(f(1))
425 print(f(2))
426 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428This will print ::
429
430 [1]
431 [1, 2]
432 [1, 2, 3]
433
434If you don't want the default to be shared between subsequent calls, you can
435write the function like this instead::
436
437 def f(a, L=None):
438 if L is None:
439 L = []
440 L.append(a)
441 return L
442
443
444.. _tut-keywordargs:
445
446Keyword Arguments
447-----------------
448
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200449Functions can also be called using :term:`keyword arguments <keyword argument>`
450of the form ``kwarg=value``. For instance, the following function::
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000453 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000454 print("if you put", voltage, "volts through it.")
455 print("-- Lovely plumage, the", type)
456 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000457
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200458accepts one required argument (``voltage``) and three optional arguments
459(``state``, ``action``, and ``type``). This function can be called in any
460of the following ways::
Georg Brandl116aa622007-08-15 14:28:22 +0000461
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200462 parrot(1000) # 1 positional argument
463 parrot(voltage=1000) # 1 keyword argument
464 parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
465 parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
466 parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
467 parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200469but all the following calls would be invalid::
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471 parrot() # required argument missing
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200472 parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
473 parrot(110, voltage=220) # duplicate value for the same argument
474 parrot(actor='John Cleese') # unknown keyword argument
Georg Brandl116aa622007-08-15 14:28:22 +0000475
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200476In a function call, keyword arguments must follow positional arguments.
477All the keyword arguments passed must match one of the arguments
478accepted by the function (e.g. ``actor`` is not a valid argument for the
479``parrot`` function), and their order is not important. This also includes
480non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).
481No argument may receive a value more than once.
482Here's an example that fails due to this restriction::
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484 >>> def function(a):
485 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +0000486 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000487 >>> function(0, a=0)
488 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530489 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000490 TypeError: function() got multiple values for keyword argument 'a'
491
492When a final formal parameter of the form ``**name`` is present, it receives a
493dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
494those corresponding to a formal parameter. This may be combined with a formal
495parameter of the form ``*name`` (described in the next subsection) which
Julien Palard51ddab82019-05-28 15:10:23 +0200496receives a :ref:`tuple <tut-tuples>` containing the positional
497arguments beyond the formal parameter list. (``*name`` must occur
498before ``**name``.) For example, if we define a function like this::
Georg Brandl116aa622007-08-15 14:28:22 +0000499
500 def cheeseshop(kind, *arguments, **keywords):
Georg Brandl5d955ed2008-09-13 17:18:21 +0000501 print("-- Do you have any", kind, "?")
Guido van Rossum0616b792007-08-31 03:25:11 +0000502 print("-- I'm sorry, we're all out of", kind)
Georg Brandl70543ac2010-10-15 15:32:05 +0000503 for arg in arguments:
504 print(arg)
Georg Brandl5d955ed2008-09-13 17:18:21 +0000505 print("-" * 40)
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200506 for kw in keywords:
Georg Brandl70543ac2010-10-15 15:32:05 +0000507 print(kw, ":", keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000508
509It could be called like this::
510
Georg Brandl5d955ed2008-09-13 17:18:21 +0000511 cheeseshop("Limburger", "It's very runny, sir.",
Georg Brandl116aa622007-08-15 14:28:22 +0000512 "It's really very, VERY runny, sir.",
Georg Brandl5d955ed2008-09-13 17:18:21 +0000513 shopkeeper="Michael Palin",
514 client="John Cleese",
515 sketch="Cheese Shop Sketch")
Georg Brandl116aa622007-08-15 14:28:22 +0000516
Martin Panter1050d2d2016-07-26 11:18:21 +0200517and of course it would print:
518
519.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521 -- Do you have any Limburger ?
522 -- I'm sorry, we're all out of Limburger
523 It's very runny, sir.
524 It's really very, VERY runny, sir.
525 ----------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000526 shopkeeper : Michael Palin
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200527 client : John Cleese
Georg Brandl116aa622007-08-15 14:28:22 +0000528 sketch : Cheese Shop Sketch
529
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200530Note that the order in which the keyword arguments are printed is guaranteed
531to match the order in which they were provided in the function call.
532
Pablo Galindob76302d2019-05-29 00:45:32 +0100533Special parameters
534------------------
535
536By default, arguments may be passed to a Python function either by position
537or explicitly by keyword. For readability and performance, it makes sense to
538restrict the way arguments can be passed so that a developer need only look
539at the function definition to determine if items are passed by position, by
540position or keyword, or by keyword.
541
542A function definition may look like:
543
544.. code-block:: none
545
546 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
547 ----------- ---------- ----------
548 | | |
549 | Positional or keyword |
550 | - Keyword only
551 -- Positional only
552
553where ``/`` and ``*`` are optional. If used, these symbols indicate the kind of
554parameter by how the arguments may be passed to the function:
555positional-only, positional-or-keyword, and keyword-only. Keyword parameters
556are also referred to as named parameters.
557
558-------------------------------
559Positional-or-Keyword Arguments
560-------------------------------
561
562If ``/`` and ``*`` are not present in the function definition, arguments may
563be passed to a function by position or by keyword.
564
565--------------------------
566Positional-Only Parameters
567--------------------------
568
569Looking at this in a bit more detail, it is possible to mark certain parameters
570as *positional-only*. If *positional-only*, the parameters' order matters, and
571the parameters cannot be passed by keyword. Positional-only parameters are
572placed before a ``/`` (forward-slash). The ``/`` is used to logically
573separate the positional-only parameters from the rest of the parameters.
574If there is no ``/`` in the function definition, there are no positional-only
575parameters.
576
577Parameters following the ``/`` may be *positional-or-keyword* or *keyword-only*.
578
579----------------------
580Keyword-Only Arguments
581----------------------
582
583To mark parameters as *keyword-only*, indicating the parameters must be passed
584by keyword argument, place an ``*`` in the arguments list just before the first
585*keyword-only* parameter.
586
587-----------------
588Function Examples
589-----------------
590
591Consider the following example function definitions paying close attention to the
592markers ``/`` and ``*``::
593
594 >>> def standard_arg(arg):
595 ... print(arg)
596 ...
597 >>> def pos_only_arg(arg, /):
598 ... print(arg)
599 ...
600 >>> def kwd_only_arg(*, arg):
601 ... print(arg)
602 ...
603 >>> def combined_example(pos_only, /, standard, *, kwd_only):
604 ... print(pos_only, standard, kwd_only)
605
606
607The first function definition, ``standard_arg``, the most familiar form,
608places no restrictions on the calling convention and arguments may be
609passed by position or keyword::
610
611 >>> standard_arg(2)
612 2
613
614 >>> standard_arg(arg=2)
615 2
616
617The second function ``pos_only_arg`` is restricted to only use positional
618parameters as there is a ``/`` in the function definition::
619
620 >>> pos_only_arg(1)
621 1
622
623 >>> pos_only_arg(arg=1)
624 Traceback (most recent call last):
625 File "<stdin>", line 1, in <module>
626 TypeError: pos_only_arg() got an unexpected keyword argument 'arg'
627
628The third function ``kwd_only_args`` only allows keyword arguments as indicated
629by a ``*`` in the function definition::
630
631 >>> kwd_only_arg(3)
632 Traceback (most recent call last):
633 File "<stdin>", line 1, in <module>
634 TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given
635
636 >>> kwd_only_arg(arg=3)
637 3
638
639And the last uses all three calling conventions in the same function
640definition::
641
642 >>> combined_example(1, 2, 3)
643 Traceback (most recent call last):
644 File "<stdin>", line 1, in <module>
645 TypeError: combined_example() takes 2 positional arguments but 3 were given
646
647 >>> combined_example(1, 2, kwd_only=3)
648 1 2 3
649
650 >>> combined_example(1, standard=2, kwd_only=3)
651 1 2 3
652
653 >>> combined_example(pos_only=1, standard=2, kwd_only=3)
654 Traceback (most recent call last):
655 File "<stdin>", line 1, in <module>
656 TypeError: combined_example() got an unexpected keyword argument 'pos_only'
657
658
659Finally, consider this function definition which has a potential collision between the positional argument ``name`` and ``**kwds`` which has ``name`` as a key::
660
661 def foo(name, **kwds):
662 return 'name' in kwds
663
664There is no possible call that will make it return ``True`` as the keyword ``'name'``
Denis Ovsienko0be7c212020-08-19 12:29:47 +0100665will always bind to the first parameter. For example::
Pablo Galindob76302d2019-05-29 00:45:32 +0100666
667 >>> foo(1, **{'name': 2})
668 Traceback (most recent call last):
669 File "<stdin>", line 1, in <module>
670 TypeError: foo() got multiple values for argument 'name'
671 >>>
672
673But using ``/`` (positional only arguments), it is possible since it allows ``name`` as a positional argument and ``'name'`` as a key in the keyword arguments::
674
675 def foo(name, /, **kwds):
676 return 'name' in kwds
677 >>> foo(1, **{'name': 2})
678 True
679
680In other words, the names of positional-only parameters can be used in
681``**kwds`` without ambiguity.
682
683-----
684Recap
685-----
686
687The use case will determine which parameters to use in the function definition::
688
689 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
690
691As guidance:
692
693* Use positional-only if you want the name of the parameters to not be
694 available to the user. This is useful when parameter names have no real
695 meaning, if you want to enforce the order of the arguments when the function
696 is called or if you need to take some positional parameters and arbitrary
697 keywords.
698* Use keyword-only when names have meaning and the function definition is
699 more understandable by being explicit with names or you want to prevent
700 users relying on the position of the argument being passed.
Adorilson Bezerrab7af4e72019-09-16 04:04:58 -0300701* For an API, use positional-only to prevent breaking API changes
Pablo Galindob76302d2019-05-29 00:45:32 +0100702 if the parameter's name is modified in the future.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
704.. _tut-arbitraryargs:
705
706Arbitrary Argument Lists
707------------------------
708
Christian Heimesdae2a892008-04-19 00:55:37 +0000709.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200710 single: * (asterisk); in function calls
Christian Heimesdae2a892008-04-19 00:55:37 +0000711
Georg Brandl116aa622007-08-15 14:28:22 +0000712Finally, the least frequently used option is to specify that a function can be
713called with an arbitrary number of arguments. These arguments will be wrapped
Georg Brandl5d955ed2008-09-13 17:18:21 +0000714up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
715zero or more normal arguments may occur. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000717 def write_multiple_items(file, separator, *args):
718 file.write(separator.join(args))
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Georg Brandl48310cd2009-01-03 21:18:54 +0000720
Guido van Rossum0616b792007-08-31 03:25:11 +0000721Normally, these ``variadic`` arguments will be last in the list of formal
Georg Brandl48310cd2009-01-03 21:18:54 +0000722parameters, because they scoop up all remaining input arguments that are
Guido van Rossum0616b792007-08-31 03:25:11 +0000723passed to the function. Any formal parameters which occur after the ``*args``
Georg Brandl48310cd2009-01-03 21:18:54 +0000724parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000725keywords rather than positional arguments. ::
Georg Brandl48310cd2009-01-03 21:18:54 +0000726
Guido van Rossum0616b792007-08-31 03:25:11 +0000727 >>> def concat(*args, sep="/"):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300728 ... return sep.join(args)
Guido van Rossum0616b792007-08-31 03:25:11 +0000729 ...
730 >>> concat("earth", "mars", "venus")
731 'earth/mars/venus'
732 >>> concat("earth", "mars", "venus", sep=".")
733 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000734
735.. _tut-unpacking-arguments:
736
737Unpacking Argument Lists
738------------------------
739
740The reverse situation occurs when the arguments are already in a list or tuple
741but need to be unpacked for a function call requiring separate positional
742arguments. For instance, the built-in :func:`range` function expects separate
743*start* and *stop* arguments. If they are not available separately, write the
Raymond Hettingerfb28fcc2019-03-27 21:03:02 -0700744function call with the ``*``\ -operator to unpack the arguments out of a list
Georg Brandl116aa622007-08-15 14:28:22 +0000745or tuple::
746
Guido van Rossum0616b792007-08-31 03:25:11 +0000747 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000748 [3, 4, 5]
749 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000750 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000751 [3, 4, 5]
752
Christian Heimesdae2a892008-04-19 00:55:37 +0000753.. index::
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300754 single: **; in function calls
Christian Heimesdae2a892008-04-19 00:55:37 +0000755
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200756In the same fashion, dictionaries can deliver keyword arguments with the
Raymond Hettingerfb28fcc2019-03-27 21:03:02 -0700757``**``\ -operator::
Georg Brandl116aa622007-08-15 14:28:22 +0000758
759 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000760 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000761 ... print("if you put", voltage, "volts through it.", end=' ')
762 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000763 ...
764 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
765 >>> parrot(**d)
766 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
767
768
769.. _tut-lambda:
770
Georg Brandlde5aff12013-10-06 10:22:45 +0200771Lambda Expressions
772------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000773
Georg Brandlde5aff12013-10-06 10:22:45 +0200774Small anonymous functions can be created with the :keyword:`lambda` keyword.
775This function returns the sum of its two arguments: ``lambda a, b: a+b``.
Georg Brandl242e6a02013-10-06 10:28:39 +0200776Lambda functions can be used wherever function objects are required. They are
Georg Brandlde5aff12013-10-06 10:22:45 +0200777syntactically restricted to a single expression. Semantically, they are just
778syntactic sugar for a normal function definition. Like nested function
779definitions, lambda functions can reference variables from the containing
780scope::
Georg Brandl116aa622007-08-15 14:28:22 +0000781
782 >>> def make_incrementor(n):
783 ... return lambda x: x + n
784 ...
785 >>> f = make_incrementor(42)
786 >>> f(0)
787 42
788 >>> f(1)
789 43
790
Georg Brandlde5aff12013-10-06 10:22:45 +0200791The above example uses a lambda expression to return a function. Another use
792is to pass a small function as an argument::
793
794 >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
795 >>> pairs.sort(key=lambda pair: pair[1])
796 >>> pairs
797 [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
798
Georg Brandl116aa622007-08-15 14:28:22 +0000799
800.. _tut-docstrings:
801
802Documentation Strings
803---------------------
804
805.. index::
806 single: docstrings
807 single: documentation strings
808 single: strings, documentation
809
Guido van Rossum0616b792007-08-31 03:25:11 +0000810Here are some conventions about the content and formatting of documentation
Georg Brandl48310cd2009-01-03 21:18:54 +0000811strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000812
813The first line should always be a short, concise summary of the object's
814purpose. For brevity, it should not explicitly state the object's name or type,
815since these are available by other means (except if the name happens to be a
816verb describing a function's operation). This line should begin with a capital
817letter and end with a period.
818
819If there are more lines in the documentation string, the second line should be
820blank, visually separating the summary from the rest of the description. The
821following lines should be one or more paragraphs describing the object's calling
822conventions, its side effects, etc.
823
824The Python parser does not strip indentation from multi-line string literals in
825Python, so tools that process documentation have to strip indentation if
826desired. This is done using the following convention. The first non-blank line
827*after* the first line of the string determines the amount of indentation for
828the entire documentation string. (We can't use the first line since it is
829generally adjacent to the string's opening quotes so its indentation is not
830apparent in the string literal.) Whitespace "equivalent" to this indentation is
831then stripped from the start of all lines of the string. Lines that are
832indented less should not occur, but if they occur all their leading whitespace
833should be stripped. Equivalence of whitespace should be tested after expansion
834of tabs (to 8 spaces, normally).
835
836Here is an example of a multi-line docstring::
837
838 >>> def my_function():
839 ... """Do nothing, but document it.
Georg Brandl48310cd2009-01-03 21:18:54 +0000840 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000841 ... No, really, it doesn't do anything.
842 ... """
843 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +0000844 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000845 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000846 Do nothing, but document it.
847
848 No, really, it doesn't do anything.
849
850
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200851.. _tut-annotations:
852
853Function Annotations
854--------------------
855
856.. sectionauthor:: Zachary Ware <zachary.ware@gmail.com>
857.. index::
858 pair: function; annotations
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300859 single: ->; function annotations
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200860 single: : (colon); function annotations
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200861
Zachary Waref3b990e2015-04-13 11:30:47 -0500862:ref:`Function annotations <function>` are completely optional metadata
Neeraj Badlani643ff712018-04-25 10:52:13 -0700863information about the types used by user-defined functions (see :pep:`3107` and
864:pep:`484` for more information).
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200865
Cheryl Sabellab7105c92018-12-24 00:09:09 -0500866:term:`Annotations <function annotation>` are stored in the :attr:`__annotations__`
867attribute of the function as a dictionary and have no effect on any other part of the
868function. Parameter annotations are defined by a colon after the parameter name, followed
869by an expression evaluating to the value of the annotation. Return annotations are
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200870defined by a literal ``->``, followed by an expression, between the parameter
871list and the colon denoting the end of the :keyword:`def` statement. The
872following example has a positional argument, a keyword argument, and the return
Zachary Waref3b990e2015-04-13 11:30:47 -0500873value annotated::
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200874
Zachary Waref3b990e2015-04-13 11:30:47 -0500875 >>> def f(ham: str, eggs: str = 'eggs') -> str:
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200876 ... print("Annotations:", f.__annotations__)
877 ... print("Arguments:", ham, eggs)
Zachary Waref3b990e2015-04-13 11:30:47 -0500878 ... return ham + ' and ' + eggs
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200879 ...
Zachary Waref3b990e2015-04-13 11:30:47 -0500880 >>> f('spam')
881 Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
882 Arguments: spam eggs
883 'spam and eggs'
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200884
Christian Heimes043d6f62008-01-07 17:19:16 +0000885.. _tut-codingstyle:
886
887Intermezzo: Coding Style
888========================
889
890.. sectionauthor:: Georg Brandl <georg@python.org>
891.. index:: pair: coding; style
892
893Now that you are about to write longer, more complex pieces of Python, it is a
894good time to talk about *coding style*. Most languages can be written (or more
895concise, *formatted*) in different styles; some are more readable than others.
896Making it easy for others to read your code is always a good idea, and adopting
897a nice coding style helps tremendously for that.
898
Christian Heimesdae2a892008-04-19 00:55:37 +0000899For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Christian Heimes043d6f62008-01-07 17:19:16 +0000900it promotes a very readable and eye-pleasing coding style. Every Python
901developer should read it at some point; here are the most important points
902extracted for you:
903
904* Use 4-space indentation, and no tabs.
905
906 4 spaces are a good compromise between small indentation (allows greater
907 nesting depth) and large indentation (easier to read). Tabs introduce
908 confusion, and are best left out.
909
910* Wrap lines so that they don't exceed 79 characters.
911
912 This helps users with small displays and makes it possible to have several
913 code files side-by-side on larger displays.
914
915* Use blank lines to separate functions and classes, and larger blocks of
916 code inside functions.
917
918* When possible, put comments on a line of their own.
919
920* Use docstrings.
921
922* Use spaces around operators and after commas, but not directly inside
923 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
924
925* Name your classes and functions consistently; the convention is to use
Julien Palard2da622f2019-07-08 23:06:32 +0200926 ``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for functions
Georg Brandl5d955ed2008-09-13 17:18:21 +0000927 and methods. Always use ``self`` as the name for the first method argument
928 (see :ref:`tut-firstclasses` for more on classes and methods).
Christian Heimes043d6f62008-01-07 17:19:16 +0000929
930* Don't use fancy encodings if your code is meant to be used in international
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000931 environments. Python's default, UTF-8, or even plain ASCII work best in any
932 case.
933
934* Likewise, don't use non-ASCII characters in identifiers if there is only the
935 slightest chance people speaking a different language will read or maintain
936 the code.
Christian Heimes043d6f62008-01-07 17:19:16 +0000937
Georg Brandl116aa622007-08-15 14:28:22 +0000938
939.. rubric:: Footnotes
940
Christian Heimes043d6f62008-01-07 17:19:16 +0000941.. [#] Actually, *call by object reference* would be a better description,
942 since if a mutable object is passed, the caller will see any changes the
943 callee makes to it (items inserted into a list).