Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. class Test1(object):
  2. incr_amount = 1
  3. def increment(self, num):
  4. return num + self.incr_amount
  5.  
  6. def increment_2(self, num):
  7. Test1.incr_amount = 2
  8. return num + self.incr_amount
  9.  
  10. a = Test1()
  11. b = Test1()
  12.  
  13. assert a.increment(10) == 11
  14. assert a.increment_2(10) == 12
  15. try:
  16. assert b.increment(10) == 11
  17. except AssertionError:
  18. pass
  19. print('b.increment fails because the incr_amount was set to something else in *a*')
  20.  
  21.  
  22. class Test2(object):
  23. def __init__(self):
  24. self.incr_amount = 1
  25.  
  26. def increment(self, num):
  27. return num + self.incr_amount
  28.  
  29. def increment_2(self, num):
  30. self.incr_amount = 2
  31. return num + self.incr_amount
  32.  
  33. a = Test2()
  34. b = Test2()
  35.  
  36. assert a.increment(10) == 11
  37. assert a.increment_2(10) == 12
  38. assert b.increment(10) == 11 # This now works because the separate instances have different values
  39.  
  40. try:
  41. assert a.increment(10) == 11
  42. except AssertionError:
  43. pass
  44. print('a.increment fails, though, because a.increment_2 set the incr_amount to something else')
  45.  
  46. # These highlight the problem with one kind of side effect in terms of bugs in the implementation
  47. # (the increment function needs to set incr_amount before it does any work). However:
  48. #
  49. # (1) In complex code, these sorts of bugs are harder to see
  50. #
  51. # (2) With threading, the same thing occurs even if the function sets the values because one thread
  52. # can be running the increment() code while the other thread can be running the increment_2() code
  53. # which creates a race condition on what self.incr_amount is set to.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement