17-more.pd 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. # More
  2. So far we have covered a majority of the various aspects of Python that you will use. In this chapter, we will cover some more aspects that will make our knowledge of Python more well-rounded.
  3. ## Passing tuples around
  4. Ever wished you could return two different values from a function? You can. All you have to do is use a tuple.
  5. ~~~
  6. >>> def get_error_details():
  7. ... return (2, 'second error details')
  8. ...
  9. >>> errnum, errstr = get_error_details()
  10. >>> errnum
  11. 2
  12. >>> errstr
  13. 'second error details'
  14. ~~~
  15. Notice that the usage of `a, b = <some expression>` interprets the result of the expression as a tuple with two values.
  16. If you want to interpret the results as `(a, <everything else>)`, then you just need to star it just like you would in function parameters:
  17. ~~~
  18. >>> a, *b = [1, 2, 3, 4]
  19. >>> a
  20. 1
  21. >>> b
  22. [2, 3, 4]
  23. ~~~
  24. This also means the fastest way to swap two variables in Python is:
  25. ~~~
  26. >>> a = 5; b = 8
  27. >>> a, b = b, a
  28. >>> a, b
  29. (8, 5)
  30. ~~~
  31. ## Special Methods
  32. There are certain methods such as the `__init__` and `__del__` methods which have special significance in classes.
  33. Special methods are used to mimic certain behaviors of built-in types. For example, if you want to use the `x[key]` indexing operation for your class (just like you use it for lists and tuples), then all you have to do is implement the `__getitem__()` method and your job is done. If you think about it, this is what Python does for the `list` class itself!
  34. Some useful special methods are listed in the following table. If you want to know about all the special methods, [see the manual](http://docs.python.org/py3k/reference/datamodel.html#specialnames).
  35. `__init__(self, ...)`
  36. : This method is called just before the newly created object is returned for usage.
  37. `__del__(self)`
  38. : Called just before the object is destroyed
  39. `__str__(self)`
  40. : Called when we use the `print` function or when `str()`is used.
  41. `__lt__(self, other)`
  42. : Called when the *less than* operator (&lt;) is used. Similarly, there are special methods for all the operators (+, &gt;, etc.)
  43. `__getitem__(self, key)`
  44. : Called when `x[key]` indexing operation is used.
  45. `__len__(self)`
  46. : Called when the built-in `len()` function is used for the sequence object.
  47. ## Single Statement Blocks
  48. We have seen that each block of statements is set apart from the rest by its own indentation level. Well, there is one caveat. If your block of statements contains only one single statement, then you can specify it on the same line of, say, a conditional statement or looping statement. The following example should make this clear:
  49. ~~~
  50. >>> flag = True
  51. >>> if flag: print('Yes')
  52. Yes
  53. ~~~
  54. Notice that the single statement is used in-place and not as a separate block. Although, you can use this for making your program *smaller*, I strongly recommend avoiding this short-cut method, except for error checking, mainly because it will be much easier to add an extra statement if you are using proper indentation.
  55. ## Lambda Forms
  56. A `lambda` statement is used to create new function objects. Essentially, the `lambda` takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function.
  57. Example (save as `lambda.py`):
  58. ~~~python
  59. points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]
  60. points.sort(key=lambda i : i['y'])
  61. print(points)
  62. ~~~
  63. Output:
  64. ~~~
  65. [{'x': 4, 'y': 1}, {'x': 2, 'y': 3}]
  66. ~~~
  67. How It Works:
  68. Notice that the `sort` method of a `list` can take a `key` parameter which determines how the list is sorted (usually we know only about ascending or descending order). In our case, we want to do a custom sort, and for that we need to write a function but instead of writing a separate `def` block for a function that will get used in only this one place, we use a lambda expression to create a new function.
  69. ## List Comprehension
  70. List comprehensions are used to derive a new list from an existing list. Suppose you have a list of numbers and you want to get a corresponding list with all the numbers multiplied by 2 only when the number itself is greater than 2. List comprehensions are ideal for such situations.
  71. Example (save as `list_comprehension.py`):
  72. ~~~python
  73. listone = [2, 3, 4]
  74. listtwo = [2*i for i in listone if i > 2]
  75. print(listtwo)
  76. ~~~
  77. Output:
  78. ~~~
  79. $ python3 list_comprehension.py
  80. [6, 8]
  81. ~~~
  82. How It Works:
  83. Here, we derive a new list by specifying the manipulation to be done (`2*i`) when some condition is satisfied (`if i > 2`). Note that the original list remains unmodified.
  84. The advantage of using list comprehensions is that it reduces the amount of boilerplate code required when we use loops to process each element of a list and store it in a new list.
  85. ## Receiving Tuples and Dictionaries in Functions
  86. There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix respectively. This is useful when taking variable number of arguments in the function.
  87. ~~~
  88. >>> def powersum(power, *args):
  89. ... '''Return the sum of each argument raised to specified power.'''
  90. ... total = 0
  91. ... for i in args:
  92. ... total += pow(i, power)
  93. ... return total
  94. ...
  95. >>> powersum(2, 3, 4)
  96. 25
  97. >>> powersum(2, 10)
  98. 100
  99. ~~~
  100. Because we have a `*` prefix on the `args` variable, all extra arguments passed to the function are stored in `args` as a tuple. If a ** prefix had been used instead, the extra parameters would be considered to be key/value pairs of a dictionary.
  101. ## The assert statement
  102. The `assert` statement is used to assert that something is true. For example, if you are very sure that you will have at least one element in a list you are using and want to check this, and raise an error if it is not true, then `assert` statement is ideal in this situation. When the assert statement fails, an `AssertionError` is raised.
  103. ~~~
  104. >>> mylist = ['item']
  105. >>> assert len(mylist) >= 1
  106. >>> mylist.pop()
  107. 'item'
  108. >>> mylist
  109. []
  110. >>> assert len(mylist) >= 1
  111. Traceback (most recent call last):
  112. File "<stdin>", line 1, in <module>
  113. AssertionError
  114. ~~~
  115. The `assert` statement should be used judiciously. Most of the time, it is better to catch exceptions, either handle the problem or display an error message to the user and then quit.
  116. ## Escape Sequences
  117. Suppose, you want to have a string which contains a single quote (`'`), how will you specify this string? For example, the string is `What's your name?`. You cannot specify `'What's your name?'` because Python will be confused as to where the string starts and ends. So, you will have to specify that this single quote does not indicate the end of the string. This can be done with the help of what is called an *escape sequence*. You specify the single quote as `\'` - notice the backslash. Now, you can specify the string as `'What\'s your name?'`.
  118. Another way of specifying this specific string would be `"What's your name?"` i.e. using double quotes. Similarly, you have to use an escape sequence for using a double quote itself in a double quoted string. Also, you have to indicate the backslash itself using the escape sequence `\\`.
  119. What if you wanted to specify a two-line string? One way is to use a triple-quoted string as shown [previously](#triple-quotes) or you can use an escape sequence for the newline character - `\n` to indicate the start of a new line. An example is `This is the first line\nThis is the second line`. Another useful escape sequence to know is the tab - `\t`. There are many more escape sequences but I have mentioned only the most useful ones here.
  120. One thing to note is that in a string, a single backslash at the end of the line indicates that the string is continued in the next line, but no newline is added. For example:
  121. ~~~python
  122. "This is the first sentence. \
  123. This is the second sentence."
  124. ~~~
  125. is equivalent to
  126. ~~~python
  127. "This is the first sentence. This is the second sentence."
  128. ~~~
  129. ### Raw String
  130. If you need to specify some strings where no special processing such as escape sequences are handled, then what you need is to specify a *raw* string by prefixing `r` or `R` to the string. An example is `r"Newlines are indicated by \n"`.
  131. Note for Regular Expression Users
  132. : Always use raw strings when dealing with regular expressions. Otherwise, a lot of backwhacking may be required. For example, backreferences can be referred to as `'\\1'` or `r'\1'`.
  133. ## Summary
  134. We have covered some more features of Python in this chapter and yet we haven't covered all the features of Python. However, at this stage, we have covered most of what you are ever going to use in practice. This is sufficient for you to get started with whatever programs you are going to create.
  135. Next, we will discuss how to explore Python further.