Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. ## objects as default parameter values
  2. Here we use the term `object` to distinguish the stateful objects (lists, dicts) from immutable data (int).
  3. ```python
  4. def appendOne(lst=[]):
  5. lst.append(1)
  6. return lst
  7.  
  8. appendOne() # -> [1]
  9. appendOne() # -> [1, 1]
  10. ```
  11. Why: The right value is resolved once and been stored. The definition above is equivalent to:
  12.  
  13. ```python
  14. _defval = []
  15.  
  16. def appendOne(lst=_defval):
  17. lst.append(1)
  18. return lst
  19. ```
  20. ## tuple is not actually immutable
  21. ```python
  22. t = ([],)
  23. t[0].append(1) # acceptable!
  24. ```
  25. Why: I consider it a bug of the CPython implementation. The implementation only reject
  26. the reassign of the references the tuple holds. The mutation inside the referenced object
  27. is unprotected.
  28.  
  29. ## the chain assignment is from left to right
  30. ```python
  31. it = it.next = ListNode()
  32. ```
  33. If this statement is writen in other common languages, it's most likely to execute the assignment from right to left.
  34. It will first create a new object, assign it to the `next` attribue of the iterator, and move the iterator to this new instance.
  35.  
  36. But in python, it's resolved in opposite way. It will first assign the instance to the iterator, then make the `next` attribute
  37. refer to itself.
  38.  
  39. ## trap in `list.__mul__`
  40. ```python
  41. lst = [[]] * 3
  42. lst[0].append(1)
  43. print(lst) # -> [[1], [1], [1]]
  44. ```
  45. Why: The expression in the list will be only resolved once. Because the `*` operator is nothing but a normal function call, the
  46. python interpretor will not treat it particularly. So the first statement is equivalent to:
  47.  
  48. ```python
  49. inner = [] # first resolve the inner object
  50. tmp = [inner] # resolve outer object
  51. lst = tmp.__mul__(3) # it will be resolved as [inner for _ in range(3)], i.e. [inner, inner, inner]
  52. ```
  53.  
  54. To construct multiple independent values in the list, we need to use list comprehension:
  55. ```python
  56. lst = [[] for _ in range(3)] # here the inner expression "[]" will be resolved multiple times
  57. lst[0].append(1)
  58. print(lst) # -> [[1], [], []]
  59. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement