|
1 .. _tut-morecontrol: |
|
2 |
|
3 *********************** |
|
4 More Control Flow Tools |
|
5 *********************** |
|
6 |
|
7 Besides the :keyword:`while` statement just introduced, Python knows the usual |
|
8 control flow statements known from other languages, with some twists. |
|
9 |
|
10 |
|
11 .. _tut-if: |
|
12 |
|
13 :keyword:`if` Statements |
|
14 ======================== |
|
15 |
|
16 Perhaps the most well-known statement type is the :keyword:`if` statement. For |
|
17 example:: |
|
18 |
|
19 >>> x = int(raw_input("Please enter an integer: ")) |
|
20 Please enter an integer: 42 |
|
21 >>> if x < 0: |
|
22 ... x = 0 |
|
23 ... print 'Negative changed to zero' |
|
24 ... elif x == 0: |
|
25 ... print 'Zero' |
|
26 ... elif x == 1: |
|
27 ... print 'Single' |
|
28 ... else: |
|
29 ... print 'More' |
|
30 ... |
|
31 More |
|
32 |
|
33 There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is |
|
34 optional. The keyword ':keyword:`elif`' is short for 'else if', and is useful |
|
35 to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ... |
|
36 :keyword:`elif` ... sequence is a substitute for the ``switch`` or |
|
37 ``case`` statements found in other languages. |
|
38 |
|
39 |
|
40 .. _tut-for: |
|
41 |
|
42 :keyword:`for` Statements |
|
43 ========================= |
|
44 |
|
45 .. index:: |
|
46 statement: for |
|
47 statement: for |
|
48 |
|
49 The :keyword:`for` statement in Python differs a bit from what you may be used |
|
50 to in C or Pascal. Rather than always iterating over an arithmetic progression |
|
51 of numbers (like in Pascal), or giving the user the ability to define both the |
|
52 iteration step and halting condition (as C), Python's :keyword:`for` statement |
|
53 iterates over the items of any sequence (a list or a string), in the order that |
|
54 they appear in the sequence. For example (no pun intended): |
|
55 |
|
56 .. One suggestion was to give a real C example here, but that may only serve to |
|
57 confuse non-C programmers. |
|
58 |
|
59 :: |
|
60 |
|
61 >>> # Measure some strings: |
|
62 ... a = ['cat', 'window', 'defenestrate'] |
|
63 >>> for x in a: |
|
64 ... print x, len(x) |
|
65 ... |
|
66 cat 3 |
|
67 window 6 |
|
68 defenestrate 12 |
|
69 |
|
70 It is not safe to modify the sequence being iterated over in the loop (this can |
|
71 only happen for mutable sequence types, such as lists). If you need to modify |
|
72 the list you are iterating over (for example, to duplicate selected items) you |
|
73 must iterate over a copy. The slice notation makes this particularly |
|
74 convenient:: |
|
75 |
|
76 >>> for x in a[:]: # make a slice copy of the entire list |
|
77 ... if len(x) > 6: a.insert(0, x) |
|
78 ... |
|
79 >>> a |
|
80 ['defenestrate', 'cat', 'window', 'defenestrate'] |
|
81 |
|
82 |
|
83 .. _tut-range: |
|
84 |
|
85 The :func:`range` Function |
|
86 ========================== |
|
87 |
|
88 If you do need to iterate over a sequence of numbers, the built-in function |
|
89 :func:`range` comes in handy. It generates lists containing arithmetic |
|
90 progressions:: |
|
91 |
|
92 >>> range(10) |
|
93 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
|
94 |
|
95 The given end point is never part of the generated list; ``range(10)`` generates |
|
96 a list of 10 values, the legal indices for items of a sequence of length 10. It |
|
97 is possible to let the range start at another number, or to specify a different |
|
98 increment (even negative; sometimes this is called the 'step'):: |
|
99 |
|
100 >>> range(5, 10) |
|
101 [5, 6, 7, 8, 9] |
|
102 >>> range(0, 10, 3) |
|
103 [0, 3, 6, 9] |
|
104 >>> range(-10, -100, -30) |
|
105 [-10, -40, -70] |
|
106 |
|
107 To iterate over the indices of a sequence, combine :func:`range` and :func:`len` |
|
108 as follows:: |
|
109 |
|
110 >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
|
111 >>> for i in range(len(a)): |
|
112 ... print i, a[i] |
|
113 ... |
|
114 0 Mary |
|
115 1 had |
|
116 2 a |
|
117 3 little |
|
118 4 lamb |
|
119 |
|
120 |
|
121 .. _tut-break: |
|
122 |
|
123 :keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops |
|
124 ========================================================================================= |
|
125 |
|
126 The :keyword:`break` statement, like in C, breaks out of the smallest enclosing |
|
127 :keyword:`for` or :keyword:`while` loop. |
|
128 |
|
129 The :keyword:`continue` statement, also borrowed from C, continues with the next |
|
130 iteration of the loop. |
|
131 |
|
132 Loop statements may have an ``else`` clause; it is executed when the loop |
|
133 terminates through exhaustion of the list (with :keyword:`for`) or when the |
|
134 condition becomes false (with :keyword:`while`), but not when the loop is |
|
135 terminated by a :keyword:`break` statement. This is exemplified by the |
|
136 following loop, which searches for prime numbers:: |
|
137 |
|
138 >>> for n in range(2, 10): |
|
139 ... for x in range(2, n): |
|
140 ... if n % x == 0: |
|
141 ... print n, 'equals', x, '*', n/x |
|
142 ... break |
|
143 ... else: |
|
144 ... # loop fell through without finding a factor |
|
145 ... print n, 'is a prime number' |
|
146 ... |
|
147 2 is a prime number |
|
148 3 is a prime number |
|
149 4 equals 2 * 2 |
|
150 5 is a prime number |
|
151 6 equals 2 * 3 |
|
152 7 is a prime number |
|
153 8 equals 2 * 4 |
|
154 9 equals 3 * 3 |
|
155 |
|
156 |
|
157 .. _tut-pass: |
|
158 |
|
159 :keyword:`pass` Statements |
|
160 ========================== |
|
161 |
|
162 The :keyword:`pass` statement does nothing. It can be used when a statement is |
|
163 required syntactically but the program requires no action. For example:: |
|
164 |
|
165 >>> while True: |
|
166 ... pass # Busy-wait for keyboard interrupt (Ctrl+C) |
|
167 ... |
|
168 |
|
169 This is commonly used for creating minimal classes such as exceptions, or |
|
170 for ignoring unwanted exceptions:: |
|
171 |
|
172 >>> class ParserError(Exception): |
|
173 ... pass |
|
174 ... |
|
175 >>> try: |
|
176 ... import audioop |
|
177 ... except ImportError: |
|
178 ... pass |
|
179 ... |
|
180 |
|
181 Another place :keyword:`pass` can be used is as a place-holder for a function or |
|
182 conditional body when you are working on new code, allowing you to keep |
|
183 thinking at a more abstract level. However, as :keyword:`pass` is silently |
|
184 ignored, a better choice may be to raise a :exc:`NotImplementedError` |
|
185 exception:: |
|
186 |
|
187 >>> def initlog(*args): |
|
188 ... raise NotImplementedError # Open logfile if not already open |
|
189 ... if not logfp: |
|
190 ... raise NotImplementedError # Set up dummy log back-end |
|
191 ... raise NotImplementedError('Call log initialization handler') |
|
192 ... |
|
193 |
|
194 If :keyword:`pass` were used here and you later ran tests, they may fail |
|
195 without indicating why. Using :exc:`NotImplementedError` causes this code |
|
196 to raise an exception, telling you exactly where the incomplete code |
|
197 is. Note the two calling styles of the exceptions above. |
|
198 The first style, with no message but with an accompanying comment, |
|
199 lets you easily leave the comment when you remove the exception, |
|
200 which ideally would be a good description for |
|
201 the block of code the exception is a placeholder for. However, the |
|
202 third example, providing a message for the exception, will produce |
|
203 a more useful traceback. |
|
204 |
|
205 .. _tut-functions: |
|
206 |
|
207 Defining Functions |
|
208 ================== |
|
209 |
|
210 We can create a function that writes the Fibonacci series to an arbitrary |
|
211 boundary:: |
|
212 |
|
213 >>> def fib(n): # write Fibonacci series up to n |
|
214 ... """Print a Fibonacci series up to n.""" |
|
215 ... a, b = 0, 1 |
|
216 ... while b < n: |
|
217 ... print b, |
|
218 ... a, b = b, a+b |
|
219 ... |
|
220 >>> # Now call the function we just defined: |
|
221 ... fib(2000) |
|
222 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 |
|
223 |
|
224 .. index:: |
|
225 single: documentation strings |
|
226 single: docstrings |
|
227 single: strings, documentation |
|
228 |
|
229 The keyword :keyword:`def` introduces a function *definition*. It must be |
|
230 followed by the function name and the parenthesized list of formal parameters. |
|
231 The statements that form the body of the function start at the next line, and |
|
232 must be indented. |
|
233 |
|
234 The first statement of the function body can optionally be a string literal; |
|
235 this string literal is the function's documentation string, or :dfn:`docstring`. |
|
236 (More about docstrings can be found in the section :ref:`tut-docstrings`.) |
|
237 There are tools which use docstrings to automatically produce online or printed |
|
238 documentation, or to let the user interactively browse through code; it's good |
|
239 practice to include docstrings in code that you write, so make a habit of it. |
|
240 |
|
241 The *execution* of a function introduces a new symbol table used for the local |
|
242 variables of the function. More precisely, all variable assignments in a |
|
243 function store the value in the local symbol table; whereas variable references |
|
244 first look in the local symbol table, then in the local symbol tables of |
|
245 enclosing functions, then in the global symbol table, and finally in the table |
|
246 of built-in names. Thus, global variables cannot be directly assigned a value |
|
247 within a function (unless named in a :keyword:`global` statement), although they |
|
248 may be referenced. |
|
249 |
|
250 The actual parameters (arguments) to a function call are introduced in the local |
|
251 symbol table of the called function when it is called; thus, arguments are |
|
252 passed using *call by value* (where the *value* is always an object *reference*, |
|
253 not the value of the object). [#]_ When a function calls another function, a new |
|
254 local symbol table is created for that call. |
|
255 |
|
256 A function definition introduces the function name in the current symbol table. |
|
257 The value of the function name has a type that is recognized by the interpreter |
|
258 as a user-defined function. This value can be assigned to another name which |
|
259 can then also be used as a function. This serves as a general renaming |
|
260 mechanism:: |
|
261 |
|
262 >>> fib |
|
263 <function fib at 10042ed0> |
|
264 >>> f = fib |
|
265 >>> f(100) |
|
266 1 1 2 3 5 8 13 21 34 55 89 |
|
267 |
|
268 Coming from other languages, you might object that ``fib`` is not a function but |
|
269 a procedure since it doesn't return a value. In fact, even functions without a |
|
270 :keyword:`return` statement do return a value, albeit a rather boring one. This |
|
271 value is called ``None`` (it's a built-in name). Writing the value ``None`` is |
|
272 normally suppressed by the interpreter if it would be the only value written. |
|
273 You can see it if you really want to using :keyword:`print`:: |
|
274 |
|
275 >>> fib(0) |
|
276 >>> print fib(0) |
|
277 None |
|
278 |
|
279 It is simple to write a function that returns a list of the numbers of the |
|
280 Fibonacci series, instead of printing it:: |
|
281 |
|
282 >>> def fib2(n): # return Fibonacci series up to n |
|
283 ... """Return a list containing the Fibonacci series up to n.""" |
|
284 ... result = [] |
|
285 ... a, b = 0, 1 |
|
286 ... while b < n: |
|
287 ... result.append(b) # see below |
|
288 ... a, b = b, a+b |
|
289 ... return result |
|
290 ... |
|
291 >>> f100 = fib2(100) # call it |
|
292 >>> f100 # write the result |
|
293 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
|
294 |
|
295 This example, as usual, demonstrates some new Python features: |
|
296 |
|
297 * The :keyword:`return` statement returns with a value from a function. |
|
298 :keyword:`return` without an expression argument returns ``None``. Falling off |
|
299 the end of a function also returns ``None``. |
|
300 |
|
301 * The statement ``result.append(b)`` calls a *method* of the list object |
|
302 ``result``. A method is a function that 'belongs' to an object and is named |
|
303 ``obj.methodname``, where ``obj`` is some object (this may be an expression), |
|
304 and ``methodname`` is the name of a method that is defined by the object's type. |
|
305 Different types define different methods. Methods of different types may have |
|
306 the same name without causing ambiguity. (It is possible to define your own |
|
307 object types and methods, using *classes*, as discussed later in this tutorial.) |
|
308 The method :meth:`append` shown in the example is defined for list objects; it |
|
309 adds a new element at the end of the list. In this example it is equivalent to |
|
310 ``result = result + [b]``, but more efficient. |
|
311 |
|
312 |
|
313 .. _tut-defining: |
|
314 |
|
315 More on Defining Functions |
|
316 ========================== |
|
317 |
|
318 It is also possible to define functions with a variable number of arguments. |
|
319 There are three forms, which can be combined. |
|
320 |
|
321 |
|
322 .. _tut-defaultargs: |
|
323 |
|
324 Default Argument Values |
|
325 ----------------------- |
|
326 |
|
327 The most useful form is to specify a default value for one or more arguments. |
|
328 This creates a function that can be called with fewer arguments than it is |
|
329 defined to allow. For example:: |
|
330 |
|
331 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): |
|
332 while True: |
|
333 ok = raw_input(prompt) |
|
334 if ok in ('y', 'ye', 'yes'): return True |
|
335 if ok in ('n', 'no', 'nop', 'nope'): return False |
|
336 retries = retries - 1 |
|
337 if retries < 0: raise IOError, 'refusenik user' |
|
338 print complaint |
|
339 |
|
340 This function can be called either like this: ``ask_ok('Do you really want to |
|
341 quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``. |
|
342 |
|
343 This example also introduces the :keyword:`in` keyword. This tests whether or |
|
344 not a sequence contains a certain value. |
|
345 |
|
346 The default values are evaluated at the point of function definition in the |
|
347 *defining* scope, so that :: |
|
348 |
|
349 i = 5 |
|
350 |
|
351 def f(arg=i): |
|
352 print arg |
|
353 |
|
354 i = 6 |
|
355 f() |
|
356 |
|
357 will print ``5``. |
|
358 |
|
359 **Important warning:** The default value is evaluated only once. This makes a |
|
360 difference when the default is a mutable object such as a list, dictionary, or |
|
361 instances of most classes. For example, the following function accumulates the |
|
362 arguments passed to it on subsequent calls:: |
|
363 |
|
364 def f(a, L=[]): |
|
365 L.append(a) |
|
366 return L |
|
367 |
|
368 print f(1) |
|
369 print f(2) |
|
370 print f(3) |
|
371 |
|
372 This will print :: |
|
373 |
|
374 [1] |
|
375 [1, 2] |
|
376 [1, 2, 3] |
|
377 |
|
378 If you don't want the default to be shared between subsequent calls, you can |
|
379 write the function like this instead:: |
|
380 |
|
381 def f(a, L=None): |
|
382 if L is None: |
|
383 L = [] |
|
384 L.append(a) |
|
385 return L |
|
386 |
|
387 |
|
388 .. _tut-keywordargs: |
|
389 |
|
390 Keyword Arguments |
|
391 ----------------- |
|
392 |
|
393 Functions can also be called using keyword arguments of the form ``keyword = |
|
394 value``. For instance, the following function:: |
|
395 |
|
396 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): |
|
397 print "-- This parrot wouldn't", action, |
|
398 print "if you put", voltage, "volts through it." |
|
399 print "-- Lovely plumage, the", type |
|
400 print "-- It's", state, "!" |
|
401 |
|
402 could be called in any of the following ways:: |
|
403 |
|
404 parrot(1000) |
|
405 parrot(action = 'VOOOOOM', voltage = 1000000) |
|
406 parrot('a thousand', state = 'pushing up the daisies') |
|
407 parrot('a million', 'bereft of life', 'jump') |
|
408 |
|
409 but the following calls would all be invalid:: |
|
410 |
|
411 parrot() # required argument missing |
|
412 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword |
|
413 parrot(110, voltage=220) # duplicate value for argument |
|
414 parrot(actor='John Cleese') # unknown keyword |
|
415 |
|
416 In general, an argument list must have any positional arguments followed by any |
|
417 keyword arguments, where the keywords must be chosen from the formal parameter |
|
418 names. It's not important whether a formal parameter has a default value or |
|
419 not. No argument may receive a value more than once --- formal parameter names |
|
420 corresponding to positional arguments cannot be used as keywords in the same |
|
421 calls. Here's an example that fails due to this restriction:: |
|
422 |
|
423 >>> def function(a): |
|
424 ... pass |
|
425 ... |
|
426 >>> function(0, a=0) |
|
427 Traceback (most recent call last): |
|
428 File "<stdin>", line 1, in ? |
|
429 TypeError: function() got multiple values for keyword argument 'a' |
|
430 |
|
431 When a final formal parameter of the form ``**name`` is present, it receives a |
|
432 dictionary (see :ref:`typesmapping`) containing all keyword arguments except for |
|
433 those corresponding to a formal parameter. This may be combined with a formal |
|
434 parameter of the form ``*name`` (described in the next subsection) which |
|
435 receives a tuple containing the positional arguments beyond the formal parameter |
|
436 list. (``*name`` must occur before ``**name``.) For example, if we define a |
|
437 function like this:: |
|
438 |
|
439 def cheeseshop(kind, *arguments, **keywords): |
|
440 print "-- Do you have any", kind, "?" |
|
441 print "-- I'm sorry, we're all out of", kind |
|
442 for arg in arguments: print arg |
|
443 print "-" * 40 |
|
444 keys = keywords.keys() |
|
445 keys.sort() |
|
446 for kw in keys: print kw, ":", keywords[kw] |
|
447 |
|
448 It could be called like this:: |
|
449 |
|
450 cheeseshop("Limburger", "It's very runny, sir.", |
|
451 "It's really very, VERY runny, sir.", |
|
452 shopkeeper='Michael Palin', |
|
453 client="John Cleese", |
|
454 sketch="Cheese Shop Sketch") |
|
455 |
|
456 and of course it would print:: |
|
457 |
|
458 -- Do you have any Limburger ? |
|
459 -- I'm sorry, we're all out of Limburger |
|
460 It's very runny, sir. |
|
461 It's really very, VERY runny, sir. |
|
462 ---------------------------------------- |
|
463 client : John Cleese |
|
464 shopkeeper : Michael Palin |
|
465 sketch : Cheese Shop Sketch |
|
466 |
|
467 Note that the :meth:`sort` method of the list of keyword argument names is |
|
468 called before printing the contents of the ``keywords`` dictionary; if this is |
|
469 not done, the order in which the arguments are printed is undefined. |
|
470 |
|
471 |
|
472 .. _tut-arbitraryargs: |
|
473 |
|
474 Arbitrary Argument Lists |
|
475 ------------------------ |
|
476 |
|
477 .. index:: |
|
478 statement: * |
|
479 |
|
480 Finally, the least frequently used option is to specify that a function can be |
|
481 called with an arbitrary number of arguments. These arguments will be wrapped |
|
482 up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments, |
|
483 zero or more normal arguments may occur. :: |
|
484 |
|
485 def write_multiple_items(file, separator, *args): |
|
486 file.write(separator.join(args)) |
|
487 |
|
488 |
|
489 .. _tut-unpacking-arguments: |
|
490 |
|
491 Unpacking Argument Lists |
|
492 ------------------------ |
|
493 |
|
494 The reverse situation occurs when the arguments are already in a list or tuple |
|
495 but need to be unpacked for a function call requiring separate positional |
|
496 arguments. For instance, the built-in :func:`range` function expects separate |
|
497 *start* and *stop* arguments. If they are not available separately, write the |
|
498 function call with the ``*``\ -operator to unpack the arguments out of a list |
|
499 or tuple:: |
|
500 |
|
501 >>> range(3, 6) # normal call with separate arguments |
|
502 [3, 4, 5] |
|
503 >>> args = [3, 6] |
|
504 >>> range(*args) # call with arguments unpacked from a list |
|
505 [3, 4, 5] |
|
506 |
|
507 .. index:: |
|
508 statement: ** |
|
509 |
|
510 In the same fashion, dictionaries can deliver keyword arguments with the ``**``\ |
|
511 -operator:: |
|
512 |
|
513 >>> def parrot(voltage, state='a stiff', action='voom'): |
|
514 ... print "-- This parrot wouldn't", action, |
|
515 ... print "if you put", voltage, "volts through it.", |
|
516 ... print "E's", state, "!" |
|
517 ... |
|
518 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} |
|
519 >>> parrot(**d) |
|
520 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised ! |
|
521 |
|
522 |
|
523 .. _tut-lambda: |
|
524 |
|
525 Lambda Forms |
|
526 ------------ |
|
527 |
|
528 By popular demand, a few features commonly found in functional programming |
|
529 languages like Lisp have been added to Python. With the :keyword:`lambda` |
|
530 keyword, small anonymous functions can be created. Here's a function that |
|
531 returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be |
|
532 used wherever function objects are required. They are syntactically restricted |
|
533 to a single expression. Semantically, they are just syntactic sugar for a |
|
534 normal function definition. Like nested function definitions, lambda forms can |
|
535 reference variables from the containing scope:: |
|
536 |
|
537 >>> def make_incrementor(n): |
|
538 ... return lambda x: x + n |
|
539 ... |
|
540 >>> f = make_incrementor(42) |
|
541 >>> f(0) |
|
542 42 |
|
543 >>> f(1) |
|
544 43 |
|
545 |
|
546 |
|
547 .. _tut-docstrings: |
|
548 |
|
549 Documentation Strings |
|
550 --------------------- |
|
551 |
|
552 .. index:: |
|
553 single: docstrings |
|
554 single: documentation strings |
|
555 single: strings, documentation |
|
556 |
|
557 There are emerging conventions about the content and formatting of documentation |
|
558 strings. |
|
559 |
|
560 The first line should always be a short, concise summary of the object's |
|
561 purpose. For brevity, it should not explicitly state the object's name or type, |
|
562 since these are available by other means (except if the name happens to be a |
|
563 verb describing a function's operation). This line should begin with a capital |
|
564 letter and end with a period. |
|
565 |
|
566 If there are more lines in the documentation string, the second line should be |
|
567 blank, visually separating the summary from the rest of the description. The |
|
568 following lines should be one or more paragraphs describing the object's calling |
|
569 conventions, its side effects, etc. |
|
570 |
|
571 The Python parser does not strip indentation from multi-line string literals in |
|
572 Python, so tools that process documentation have to strip indentation if |
|
573 desired. This is done using the following convention. The first non-blank line |
|
574 *after* the first line of the string determines the amount of indentation for |
|
575 the entire documentation string. (We can't use the first line since it is |
|
576 generally adjacent to the string's opening quotes so its indentation is not |
|
577 apparent in the string literal.) Whitespace "equivalent" to this indentation is |
|
578 then stripped from the start of all lines of the string. Lines that are |
|
579 indented less should not occur, but if they occur all their leading whitespace |
|
580 should be stripped. Equivalence of whitespace should be tested after expansion |
|
581 of tabs (to 8 spaces, normally). |
|
582 |
|
583 Here is an example of a multi-line docstring:: |
|
584 |
|
585 >>> def my_function(): |
|
586 ... """Do nothing, but document it. |
|
587 ... |
|
588 ... No, really, it doesn't do anything. |
|
589 ... """ |
|
590 ... pass |
|
591 ... |
|
592 >>> print my_function.__doc__ |
|
593 Do nothing, but document it. |
|
594 |
|
595 No, really, it doesn't do anything. |
|
596 |
|
597 |
|
598 .. _tut-codingstyle: |
|
599 |
|
600 Intermezzo: Coding Style |
|
601 ======================== |
|
602 |
|
603 .. sectionauthor:: Georg Brandl <georg@python.org> |
|
604 .. index:: pair: coding; style |
|
605 |
|
606 Now that you are about to write longer, more complex pieces of Python, it is a |
|
607 good time to talk about *coding style*. Most languages can be written (or more |
|
608 concise, *formatted*) in different styles; some are more readable than others. |
|
609 Making it easy for others to read your code is always a good idea, and adopting |
|
610 a nice coding style helps tremendously for that. |
|
611 |
|
612 For Python, :pep:`8` has emerged as the style guide that most projects adhere to; |
|
613 it promotes a very readable and eye-pleasing coding style. Every Python |
|
614 developer should read it at some point; here are the most important points |
|
615 extracted for you: |
|
616 |
|
617 * Use 4-space indentation, and no tabs. |
|
618 |
|
619 4 spaces are a good compromise between small indentation (allows greater |
|
620 nesting depth) and large indentation (easier to read). Tabs introduce |
|
621 confusion, and are best left out. |
|
622 |
|
623 * Wrap lines so that they don't exceed 79 characters. |
|
624 |
|
625 This helps users with small displays and makes it possible to have several |
|
626 code files side-by-side on larger displays. |
|
627 |
|
628 * Use blank lines to separate functions and classes, and larger blocks of |
|
629 code inside functions. |
|
630 |
|
631 * When possible, put comments on a line of their own. |
|
632 |
|
633 * Use docstrings. |
|
634 |
|
635 * Use spaces around operators and after commas, but not directly inside |
|
636 bracketing constructs: ``a = f(1, 2) + g(3, 4)``. |
|
637 |
|
638 * Name your classes and functions consistently; the convention is to use |
|
639 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions |
|
640 and methods. Always use ``self`` as the name for the first method argument |
|
641 (see :ref:`tut-firstclasses` for more on classes and methods). |
|
642 |
|
643 * Don't use fancy encodings if your code is meant to be used in international |
|
644 environments. Plain ASCII works best in any case. |
|
645 |
|
646 |
|
647 .. rubric:: Footnotes |
|
648 |
|
649 .. [#] Actually, *call by object reference* would be a better description, |
|
650 since if a mutable object is passed, the caller will see any changes the |
|
651 callee makes to it (items inserted into a list). |
|
652 |