0

i really do not understand why the behaviours are not the same.

I have read https://stackoverflow.com/a/9172325/6581137 but i do not understand why iadd and += would produce differents bytecodes.

Using Python 3.6

class flist:

    def __init__(self):
            self.a = 1

    def __iadd__(self, nb):
            self.a = self.a + nb

    def __repr__(self):
            return str(self.a)

t = (flist(), flist(), flist())
print(t)
try:
    t[1].__iadd__(2)
    #t[1] += 2
except:
    print("exception")
print(t)

Output: t[1] is incremented by 2, normal.

(1, 1, 1)
(1, 3, 1)

But,

class flist:

    def __init__(self):
            self.a = 1

    def __iadd__(self, nb):
            self.a = self.a + nb

    def __repr__(self):
            return str(self.a)

t = (flist(), flist(), flist())
print(t)
try:
    #t[1].__iadd__(2)
    t[1] += 2
except:
    print("exception")
print(t)

Output: t[1] is incremented by 2, but it raises an exception ?

(1, 1, 1)
exception
(1, 3, 1)

Thanks

D.louis
  • 9
  • 1
  • 2
    This is also a good example of why you don't want to do something like `except: print("exception")`. You've lost the real exception message which would have pointed you in the direction of the problem. – HFBrowning Dec 25 '17 at 18:55
  • Hello, @HFBrowning, i'm not asking what is the problem about the exception, i'm asking why += and __iadd__ produce differents outputs. Thanks for help – D.louis Dec 25 '17 at 19:36
  • 2
    Understood. However, my point is that in the other question that you're now linked to, the OP there was getting `TypeError: 'tuple' object does not support item assignment`. This told them at least some information about what the problem was - and you can google these error messages to get more information. For debugging this is critical. It's always better to try to catch the most specific exception possible. And if you want to catch everything, at least make sure to use `except Exception as e: print(e)` – HFBrowning Dec 25 '17 at 19:58

0 Answers0