Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Test1(object):
- incr_amount = 1
- def increment(self, num):
- return num + self.incr_amount
- def increment_2(self, num):
- Test1.incr_amount = 2
- return num + self.incr_amount
- a = Test1()
- b = Test1()
- assert a.increment(10) == 11
- assert a.increment_2(10) == 12
- try:
- assert b.increment(10) == 11
- except AssertionError:
- pass
- print('b.increment fails because the incr_amount was set to something else in *a*')
- class Test2(object):
- def __init__(self):
- self.incr_amount = 1
- def increment(self, num):
- return num + self.incr_amount
- def increment_2(self, num):
- self.incr_amount = 2
- return num + self.incr_amount
- a = Test2()
- b = Test2()
- assert a.increment(10) == 11
- assert a.increment_2(10) == 12
- assert b.increment(10) == 11 # This now works because the separate instances have different values
- try:
- assert a.increment(10) == 11
- except AssertionError:
- pass
- print('a.increment fails, though, because a.increment_2 set the incr_amount to something else')
- # These highlight the problem with one kind of side effect in terms of bugs in the implementation
- # (the increment function needs to set incr_amount before it does any work). However:
- #
- # (1) In complex code, these sorts of bugs are harder to see
- #
- # (2) With threading, the same thing occurs even if the function sets the values because one thread
- # can be running the increment() code while the other thread can be running the increment_2() code
- # which creates a race condition on what self.incr_amount is set to.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement